Javascript loop through object array?

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

I am trying to loop through the following:

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


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

    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
    
    0 讨论(0)
  • 2020-11-28 05:37

    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]);
     }
    
    0 讨论(0)
  • 2020-11-28 05:37

    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".

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

    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]);
                   }
               }
           }
        }
    
    0 讨论(0)
  • 2020-11-28 05:40

    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];
        // ...
    }
    
    0 讨论(0)
  • 2020-11-28 05:52

    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]);
        });
    });

    0 讨论(0)
提交回复
热议问题