迭代 javascript "subobjects" 的对象属性

Iterating javascript Object properties of "subobjects"

我有一个这样的对象:

customers:
{
  239:
  {
    firstname : "Peter",
    lastname  : "Johnson"
  },
  242:
  {
    firstname : "Peter",
    lastname  : "Johnson"
  },
  etc...
}

如何迭代获取所有名字,最好使用 jQuery?编号的 ID 不一定按顺序排列。

var data = {customers:
{
  239:
  {
    firstname : "Peter",
    lastname  : "Johnson"
  },
  242:
  {
    firstname : "Peter",
    lastname  : "Johnson"
  }
}};


$.each(data,function(k,v){
  $.each(v,function(key,value){
    console.log(key+"    "+value.firstname);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

你可以在 jquery

var customers = {
    239: {
        firstname: "Peter",
        lastname: "Johnson"
    },
    242: {
        firstname: "Paul",
        lastname: "Johnson"
    },
};

var firstnames = Object.keys(customers)
    .reduce((p, c) => 
        p.push(customers[c].firstname) && p, []);

document.write(firstnames.join(', ')); // "Peter, Paul"

要遍历object,并获取每个子对象的项目,您可以使用$.each来实现,例如:

var customers = {
  239:
  {
    firstname : "Peter",
    lastname  : "Johnson"
  },
  242:
  {
    firstname : "Peter",
    lastname  : "Johnson"
  }
};

var firstnamesInArray = [],
        firstnamesInObject = [];

// The $.each requires an object/array as first param, and a function as second param.
// And it'll iterate through the object and call the passed in function with (key, value).
$.each(customers, function(index, item) {
  // So at here, you'll get, for example: index as 239, and item as {firstname: "Peter", lastname: "Johnson"}.
  
  // Do anything with the sub item.
  console.log(item.firstname);
  
  // You can also get the targets to arrayform or object form.
  firstnamesInArray.push(item.firstname);
  firstnamesInObject[index] = item.firstname;
});

console.log("Get into array:", firstnamesInArray);
console.log("Get into object:", firstnamesInObject);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>