Javascript loop through object array?

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

I am trying to loop through the following:

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


        
9条回答
  •  孤独总比滥情好
    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);
     });
    

提交回复
热议问题