77

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

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]

Any ideas what im doing wrong?

isherwood
  • 58,414
  • 16
  • 114
  • 157
Alosyius
  • 8,771
  • 26
  • 76
  • 120
  • 2
    `console.log(obj, prop);` – zerkms Oct 22 '13 at 22:21
  • 3
    [You'll generally want to try to avoid using `for..in` for `Array`s.](http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea) – Jonathan Lonowski Oct 22 '13 at 22:21
  • The only credible reason not to use for..in with an Array is that the properties may not be returned in the expected order. Otherwise, it's no better or worse than using for..in on any other Object (unexpected properties, properties from the `[[Prototype]]`, etc.). – RobG Oct 22 '13 at 22:31

13 Answers13

131

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:

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

Unless data was set to messages before the given snippet.

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

for (var i = 0, l = data.messages.length; i < l; i++) {
    var obj = data.messages[i];
    // ...
}
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
  • Thanks a ton for helping me change to a regular for loop as well! Accepting as soon as possible. – Alosyius Oct 22 '13 at 22:31
  • 5
    Why should he consider using a normal `for` loop? – Travis Heeter Apr 19 '17 at 13:08
  • 5
    @TravisHeeter `for..in` treats the array as a plain object, iterating all enumerable keys in an order that isn't guaranteed, rather than just its indices, `0` to `length - 1`. At times, that may actually be desired. Typically not. – [Why is using "for...in" with array iteration a bad idea?](https://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-a-bad-idea) – Jonathan Lonowski Apr 19 '17 at 19:33
  • 1
    @JonathanLonowski Thanks, maybe you can add that to your answer? – Travis Heeter Apr 19 '17 at 20:37
28

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

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

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

sandeep rajbhandari
  • 1,268
  • 1
  • 12
  • 12
18

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

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

Do .forEach on array using arrow function

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

Do .map on array using arrow function

 data.messages.map((obj, i) => {
     console.log("msgFrom", obj.msgFrom);
     console.log("msgBody", obj.msgBody);
 });
Hemadri Dasari
  • 32,666
  • 37
  • 119
  • 162
15

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]);
               }
           }
       }
    }
JustAndrei
  • 863
  • 4
  • 17
8

Iterations

Method 1: forEach method

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

Method 2: for..of method

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(let key in messages){
       console.log(messages[key]);
 }
slayer
  • 214
  • 4
  • 11
Arshid KV
  • 9,631
  • 3
  • 35
  • 36
7

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

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:

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

And both of them are outputting the following:

// Audi
// BMW
// Ferrari
// Mercedes
// Maserati
Tarvo Mäesepp
  • 4,477
  • 3
  • 44
  • 92
4

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)

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]);
    });
});
Booster2ooo
  • 1,373
  • 9
  • 11
1

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:

var person={
    first_name:"johnny",
    last_name: "johnson",
    phone:"703-3424-1111"
};
Gene
  • 10,819
  • 1
  • 66
  • 58
1
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);
 });
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 04 '22 at 23:21
0

To reference the contents of the single array containing 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

e.g. 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}]

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

sarora
  • 913
  • 9
  • 20
0
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);
    }
  }
Vishwanath
  • 176
  • 1
  • 14
  • 2
    While your code may provide the answer to the question, please add context/explanation to it so others will have some idea what it does and why it is there. – Lin Du Dec 08 '19 at 04:23
0

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}` )
}
antelove
  • 3,216
  • 26
  • 20
-2
    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;
  • Thank you for this code snippet, which might provide some limited, immediate help. A [proper explanation](https://meta.stackexchange.com/q/114762/9193372) would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please edit your answer to add some explanation, including the assumptions you’ve made. – Syscall Mar 24 '21 at 14:22