I am trying to loop through the following:
{
\"messages\": [{
\"msgFrom\": \"13223821242\",
\"msgBody\": \"Hi there\"
}, {
\"
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
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]);
}
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".
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]);
}
}
}
}
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];
// ...
}
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]);
});
});