繁体   English   中英

遍历数组中的对象

[英]Looping through objects in array

我正在循环通过数组内的二维对象。 我目前通过以下方式执行此操作:

我的数组看起来像这样

var myarray = [
    0: {
          child_obj: {}
       }
    1: {//etc}
];

我像这样遍历第二层对象

jQuery.each(myarray, function(i, first) {
    jQuery.each(first.child_obj, function(j, second) {
        //do stuff
     }
    });
});

这就是一个循环。 它工作正常,但看起来并不整洁,我觉得可能会有更好(更短)的方法来做到这一点。 我这样做的原因是因为我需要对所有child_obj

值得一提:

  • 我使用jQuery.each()因为它允许循环对象,而for() .map()等无法正确处理。
  • 我无法更改数组的结构或其内容
  • 我不需要使用索引(参数ij )。

有没有更好的办法?

如果您想抛弃jQuery(并且.each中的速度很慢)并使用ES2015 +

 var myarray = [ { child_obj: {a:1,b:2,c:3} }, { child_obj: {a:4,b:5,c:6}, child_obj2: {a:7,b:8,c:9} } ]; // specific rewrite of your code would be myarray.forEach(obj => Object.values(obj.child_obj).forEach(value => { console.log(value); })); console.log('-------'); // other examples myarray.forEach(obj => Object.values(obj).forEach(value => { // do things with each "child object" console.log(value); })); myarray.forEach(obj => Object.values(obj).forEach(child => Object.values(child).forEach(value => { // do things with each property in each child object console.log(value); }))); 

这不是更好的方法,更像是替代方法。

for (var i = 0; i < myarray.length; i++)
{
  var child_obj = myarray[i].child_obj;
  // get the keys of this object
  var keys = Object.keys(child_obj);

  // loop all those keys
  for (var keyi = 0; keyi < keys.length; keyi++)
  {
    var key  = keys[keyi];
    // get the objects item based on key;
    var item = child_obj[key];
  }
}

但是在这里,您可以在迭代原始var时直接更改其值。

希望能有所帮助

使用underscore-js库,您可以执行以下操作:

var first = _.map(myarray, element => { return element.child_obj; });
_.each(first, element => {/*do stuff*/});

您可以在forin循环中使用forEach:

myArray.forEach(function(obj){
for(var i in obj){
// do stuff
}
})

天真的递归方法可用于原始类型:

 function forEachPrimitive(o, f, k) { if (o !== Object(o)) f(k, o) else for (k in o) forEachPrimitive(o[k], f, k) } var obj = [ { x: { a: '0', b: true, c: 2 } }, { y: { d: /3/, e: null, f: undefined } } ] forEachPrimitive(obj, console.log) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM