简体   繁体   English

如何循环遍历 JavaScript object 数组?

[英]How can I loop through a JavaScript object array?

I am trying to loop through the following:我正在尝试遍历以下内容:

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

I want to retrieve msgFrom and 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?任何想法我做错了什么?

It appears you may just have missed the "messages" property in the data , so the loop is likely iterating the root Object rather than the Array :看来您可能只是错过了data"messages"属性,因此循环可能会迭代根Object而不是Array

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

Unless data was set to messages before the given snippet.除非在给定代码段之前将data设置为messages

Though, you should consider changing that to a normal for loop for the Array :不过,您应该考虑将其更改为Array的普通for循环:

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

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

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]);
               }
           }
       }
    }

All the answers provided here uses normal function but these days most of our code uses arrow functions in ES6.这里提供的所有答案都使用普通函数,但现在我们的大部分代码都使用 ES6 中的箭头函数。 I hope my answer will help readers on how to use arrow function when we do iteration over array of objects我希望我的回答能帮助读者在我们对对象数组进行迭代时如何使用箭头函数

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);
 });

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

Iterations迭代次数

Method 1: forEach method方法一: forEach方法

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

Method 2: for..of method方法二: 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..in method方法二: for..in方法

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

The suggested for loop is quite fine but you have to check the properties with hasOwnProperty .建议的 for 循环非常好,但您必须使用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 )我宁愿建议使用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]); }); });

To reference the contents of the single array containing one or more objects ie 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] 添加到查询中获取第一个数组元素

eg messages[0] will reference the object {"a":1,"b":2} as opposed to just messages which 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”。

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);
    }
  }

Here is a generic way to loop through the field objects in an object (person):这是循环遍历对象(人)中的字段对象的通用方法:

for (var property in person) {
    console.log(property,":",person[property]);
}

The person obj looks like this:人 obj 看起来像这样:

var person={
    first_name:"johnny",
    last_name: "johnson",
    phone:"703-3424-1111"
};

 let data = { "messages": [{ "msgFrom": "13223821242", "msgBody": "Hi there" }, { "msgFrom": "Bill", "msgBody": "Hello;" }] } for ( i = 0. i < data.messages;length. i++ ) { console.log( `Message from ${data.messages[i]:msgFrom}. ${data.messages[i].msgBody}` ) }

let data = {
      "messages": [{
           "msgFrom": "13223821242",
           "msgBody": "Hi there"
       }, 
{
          "msgFrom": "Bill",
          "msgBody": "Hello!"
       }]
 }
 data.messages.forEach((obj, i) => {
     console.log("msgFrom", obj.msgFrom + " msgBody", obj.msgBody);
 });
arr = [{food:"Mandazi", Price: 5},{food:"Black Tea", Price: 20},{food:"Black Coffee", Price: 20}
    ];
    txt = "";
    for (i = 0; i ";
    }
    document.getElementById("show").innerHTML = txt;

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

相关问题 如何在JavaScript中遍历此数组? - How can I loop through this array in javascript? 如何循环通过 object(对于简单的数学解释器,在 Javascript 中) - How can I loop through an object (for a simple math interpreter, in Javascript) 如何遍历 javascript 中的这个对象数组? - How can I loop through this array of objects in javascript? 如何使用 Javascript 简单地遍历数组? - How can I simply loop through an array using Javascript? 如何使用 javascript 遍历这个数组? - How can I loop through this array using javascript? 如何循环遍历 object 中的嵌套数组? - How can I loop through a nested array within an object? 如何循环遍历 Javascript 对象数组,将对象指定为其中其他对象的子对象? 树/层次结构 - How can I loop through a Javascript object array assigning objects as children of other objects within? Tree/hierarchical structure 使用JavaScript遍历对象数组 - Loop through object array with javascript 我如何循环遍历数组中每个 object 的属性,每个 object 的属性都不同。 这是 Javascript - How do i loop through the properties of each object in the array, the properties are different in each object. This is Javascript JavaScript嵌套对象数组,如何遍历数组的“ KEY”? - JavaScript nested object array, How to loop through the 'KEY' of array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM