迭代javascript对象属性" subobjects"

时间:2015-11-24 12:04:04

标签: javascript jquery object iteration

我有一个这样的对象:

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

如何迭代获取所有firstnames,最好使用jQuery?编号的ID不一定是顺序的。

3 个答案:

答案 0 :(得分:2)

要遍历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>

答案 1 :(得分:0)

&#13;
&#13;
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);
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

您可以在jquery

中执行此操作

答案 2 :(得分:0)

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"