Javascript loop through object array?

后端 未结 9 2097
执念已碎
执念已碎 2020-11-28 04:55

I am trying to loop through the following:

{
    \"messages\": [{
        \"msgFrom\": \"13223821242\",
        \"msgBody\": \"Hi there\"
    }, {
        \"         


        
相关标签:
9条回答
  • 2020-11-28 05:56

    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

    0 讨论(0)
  • 2020-11-28 05:59

    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);
     });
    
    0 讨论(0)
  • 2020-11-28 06:01
    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);
        }
      }
    
    0 讨论(0)
提交回复
热议问题