Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript loop through object array?

Tags:

javascript

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?

like image 210
Alosyius Avatar asked Oct 22 '13 22:10

Alosyius


People also ask

How do you loop through an object in an array?

To iterate through an array of objects in JavaScript, you can use the forEach() method aong with the for...in loop. The outer forEach() loop is used to iterate through the objects array. We then use the for...in loop to iterate through the properties of an individual object. ✌️ Like this article?

Can you loop through an object JavaScript?

Object. key(). It returns the values of all properties in the object as an array. You can then loop through the values array by using any of the array looping methods.

How do I iterate an array of objects in es6?

In es6 we have a forEach method which helps us to iterate over the array of objects. forEach methods takes the callback function as an argument and runs on each object present in the array.


2 Answers

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];     // ... } 
like image 170
Jonathan Lonowski Avatar answered Oct 28 '22 05:10

Jonathan Lonowski


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

like image 22
sandeep rajbhandari Avatar answered Oct 28 '22 05:10

sandeep rajbhandari