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