简体   繁体   English

用对象循环遍历数组

[英]Loop through array with objects

I have the following problem which i can't solve for 2 days now. 我有以下问题,现在两天都无法解决。 I have an array . 我有一个数组

And I try to loop over it with next for..in loop 我尝试用next for..in循环遍历它

for (var key in products2) {
    if (products2.hasOwnProperty(key)) {
        console.log(products2[key].properties);
    }
}

But I can't output the value of properties object. 但是我无法输出properties对象的值。 This array is a list of products and each product has own properties. 该数组是产品列表,每个产品都有自己的属性。

You can use Lodash: 您可以使用Lodash:

_.forEach([1, 2], function(value, index) {
    console.log(value, index);
});

Or you could use JavaScript: 或者您可以使用JavaScript:

var array = [1, 2]
for (var i in array) {
   alert(array[i]);
}
for (var key in products2) {
    console.log(products2[key].properties);
}

There is no " Key " property in " produts2 " array. produts2 ”数组中没有“ Key ”属性。 Key variable is index of the "products2" array. 关键变量是“ products2”数组的索引。 Since if condition is not getting True, console statement is not getting executed. 由于如果条件未变为True,则不会执行控制台语句。

首先,使用JSON.parse(product2)将其转换为对象,然后使用您的代码

It looks like an array with objects. 它看起来像是带有对象的数组。

[{...}, {...}, {...}, ...]

For iterating the elements, you could use Array#forEach 为了迭代元素,可以使用Array#forEach

products2.forEach(function (o) {
    Object.keys(o).forEach(function (k) {
        console.log(k, o[k]); // show key and value
    });
});

Try this 尝试这个

for (var i in products2) {
  for (key in products2[i]) {
    console.log(key + ":" + products2[i][key]);
  }
}

You have an array of objects. 您有一组对象。 So first you will have to iterate through array items then you can iterate through its keys. 因此,首先您必须遍历数组项,然后才能遍历其键。

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

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