【问题标题】:Iterating javascript Object properties of "subobjects"迭代“子对象”的javascript对象属性
【发布时间】:2016-02-26 20:52:58
【问题描述】:

我有一个这样的对象:

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

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

【问题讨论】:

  • $.each(customers, function(index, item) { console.log(item.firstname);});
  • @fuyushimoya .maparray 合作
  • 谢谢指出。
  • @fuyushimoya,我喜欢你的解决方案。简单易懂。请把它作为一个答案,这样我就可以把它变成“接受的答案”:)

标签: javascript jquery object iteration


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    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"

    【讨论】:

      【解决方案3】:

      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 中这样做

      【讨论】:

        猜你喜欢
        • 2013-02-12
        • 2011-06-18
        • 2015-08-29
        • 2021-12-04
        • 2023-03-24
        • 2010-11-08
        • 1970-01-01
        • 1970-01-01
        • 2015-09-22
        相关资源
        最近更新 更多