How can I loop through a JavaScript object array?

Javascript

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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];
    // ...
}

Solution 2 - Javascript

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

Solution 3 - Javascript

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

Solution 4 - Javascript

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

Solution 5 - Javascript

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

Solution 6 - Javascript

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

Solution 7 - Javascript

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

Solution 8 - Javascript

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".

Solution 9 - Javascript

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

Solution 10 - Javascript

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

Solution 11 - Javascript

arr = [{food:"Mandazi", Price: 5},{food:"Black Tea", Price: 20},{food:"Black Coffee", Price: 20}
];
txt = "";
for (i = 0; i < arr.length; i++) {
txt += arr[i].food + "
"; } document.getElementById("show").innerHTML = txt;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlosyiusView Question on Stackoverflow
Solution 1 - JavascriptJonathan LonowskiView Answer on Stackoverflow
Solution 2 - Javascriptsandeep rajbhandariView Answer on Stackoverflow
Solution 3 - JavascriptJustAndreiView Answer on Stackoverflow
Solution 4 - JavascriptHemadri DasariView Answer on Stackoverflow
Solution 5 - JavascriptArshid KVView Answer on Stackoverflow
Solution 6 - JavascriptTarvo MäeseppView Answer on Stackoverflow
Solution 7 - JavascriptBooster2oooView Answer on Stackoverflow
Solution 8 - JavascriptsaroraView Answer on Stackoverflow
Solution 9 - JavascriptVishwanathView Answer on Stackoverflow
Solution 10 - JavascriptGeneView Answer on Stackoverflow
Solution 11 - JavascriptmaryrobicodesView Answer on Stackoverflow