javascript Javascript循环遍历对象数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19529403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 15:53:35  来源:igfitidea点击:

Javascript loop through object array?

javascript

提问by Alosyius

I am trying to loop through the following:

我正在尝试遍历以下内容:

{
    "messages": [{
        "msgFrom": "13223821242",
        "msgBody": "Hi there"
    }, {
        "msgFrom": "Bill",
        "msgBody": "Hello!"
    }]
}

I want to retrieve msgFromand msgBody

我想检索msgFrommsgBody

I've tried:

我试过了:

        for (var key in data) {
           var obj = data[key];
           for (var prop in obj) {
              if(obj.hasOwnProperty(prop)){
                console.log(prop + " = " + obj[prop]);
              }
           }
        }

But the console log prints [Object]

但控制台日志打印 [Object]

Any ideas what im doing wrong?

任何想法我做错了什么?

回答by Jonathan Lonowski

It appears you may just have missed the "messages"property in the data, so the loop is likely iterating the root Objectrather than the Array:

看来您可能只是错过了 中的"messages"属性data,因此循环可能会迭代根Object而不是Array

for (var key in data.messages) {
    var obj = data.messages[key];
    // ...
}

Unless datawas set to messagesbefore the given snippet.

除非在给定代码段之前data设置为messages

Though, you should consider changing that to a normal forloop for the Array:

不过,您应该考虑将其更改为正常for循环Array

for (var i = 0, l = data.messages.length; i < l; i++) {
    var obj = data.messages[i];
    // ...
}

回答by JustAndrei

In your script, data is your whole object.

在您的脚本中,数据是您的整个对象。

key is "messages", which is an array you need to iterate through like this:

关键是“消息”,这是一个您需要像这样迭代的数组:

    for (var key in data) {
       var arr = data[key];
       for( var i = 0; i < arr.length; i++ ) {
           var obj = arr[ i ];
           for (var prop in obj) {
               if(obj.hasOwnProperty(prop)){
                   console.log(prop + " = " + obj[prop]);
               }
           }
       }
    }

回答by sandeep rajbhandari

You can use forEach method to iterate over array of objects.

您可以使用 forEach 方法迭代对象数组。

data.messages.forEach(function(message){
    console.log(message)
});

Refer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

参考:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

回答by Hemadri Dasari

All the answers provided here uses normal function but these days most of our code uses arrow functions in ES6. I hope my answer will help readers on how to use arrow function when we do iteration over array of objects

这里提供的所有答案都使用普通函数,但现在我们的大部分代码都使用 ES6 中的箭头函数。我希望我的回答能帮助读者在我们对对象数组进行迭代时如何使用箭头函数

let data = {
      "messages": [{
           "msgFrom": "13223821242",
           "msgBody": "Hi there"
       }, {
          "msgFrom": "Bill",
          "msgBody": "Hello!"
       }]
 }

Do .forEach on array using arrow function

使用箭头函数在数组上执行 .forEach

 data.messages.forEach((obj, i) => {
     console.log("msgFrom", obj.msgFrom);
     console.log("msgBody", obj.msgBody);
 });

Do .map on array using arrow function

使用箭头函数在数组上做 .map

 data.messages.map((obj, i) => {
     console.log("msgFrom", obj.msgFrom);
     console.log("msgBody", obj.msgBody);
 });

回答by Booster2ooo

The suggested for loop is quite fine but you have to check the properties with hasOwnProperty. I'd rather suggest using Object.keys()that only returns 'own properties' of the object (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys)

建议的 for 循环很好,但您必须使用hasOwnProperty. 我宁愿建议使用Object.keys()只返回对象的“自己的属性”(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

var data = {
    "messages": [{
        "msgFrom": "13223821242",
        "msgBody": "Hi there"
    }, {
        "msgFrom": "Bill",
        "msgBody": "Hello!"
    }]
};

data.messages.forEach(function(message, index) {
    console.log('message index '+ index);
    Object.keys(message).forEach(function(prop) {    
        console.log(prop + " = " + message[prop]);
    });
});

回答by Arshid KV

Iterations

迭代次数

Method 1:forEachmethod

方法一:forEach方法

messages.forEach(function(message) {
   console.log(message);
}


Method 2:for..ofmethod

方法二:for..of方法

for(let message of messages){
   console.log(message);
}

Note: This method might not work with objects, such as:

注意:此方法可能不适用于对象,例如:

let obj = { a: 'foo', b: { c: 'bar', d: 'daz' }, e: 'qux' }


Method 2:for..inmethod

方法二:for..in方法

for(let key in messages){
       console.log(messages[key]);
 }

回答by Tarvo M?esepp

To loop through an object array or just array in javascript, you can do the following:

要循环遍历对象数组或仅在 javascript 中的数组,您可以执行以下操作:

var cars = [{name: 'Audi'}, {name: 'BMW'}, {name: 'Ferrari'}, {name: 'Mercedes'}, {name: 'Maserati'}];

for(var i = 0; i < cars.length; i++) {
    console.log(cars[i].name);
}

There is also the forEach()function, which is more "javascript-ish" and also less code but more complicated for its syntax:

还有forEach()函数,它更像“javascript-ish”,代码也更少,但语法更复杂:

cars.forEach(function (car) {
    console.log(car.name);
});

And both of them are outputting the following:

他们都输出以下内容:

// Audi
// BMW
// Ferrari
// Mercedes
// Maserati

回答by Vishwanath

for (let key in data) {
    let value = data[key];
    for (i = 0; i < value.length; i++) {
      console.log(value[i].msgFrom);
      console.log(value[i].msgBody);
    }
  }

回答by sarora

To reference the contents of the single arraycontaining one or more objects i.e. everything in the brackets of something like this {messages: [{"a":1,"b":2}] } ,just add [0] to the query to get the first array element

要引用包含一个或多个对象的单个数组的内容,即 {messages: [{"a":1,"b":2}] } 括号中的所有内容,只需将 [0] 添加到查询中获取第一个数组元素

e.g. messages[0]will reference the object {"a":1,"b":2} as opposed to just messageswhich would reference the entire array [{"a":1,"b":2}]

例如消息[0]将引用对象{ “一”:1, “B”:2},而不是仅仅消息,其将引用整个阵列[{ “一”:1, “B”:2}]

from there you can work with the result as typical object and use Object.keys for example to get "a" and "b".

从那里您可以将结果作为典型对象使用,并使用 Object.keys 来获取“a”和“b”。