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?
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?
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.
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.
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]; // ... }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With