Gregory Iiams
Gregory Iiams

Reputation: 5

node.js loop through object array

I'm trying to store multiple objects from an array as a variable. I really hope that makes sense.

So, I am able to store one element of the array in a variable.

var data = msg.payload.data;
msg.payload = data.observations[0].clientMac;
return msg;

But instead of just the MAC from key 0, I want to loop through each key, grab the mac, and store it in a new array. I'm just not sure how to do that.

Below is a sample of how the data is formatted:

    {
    "apMac" : "aa:bb:cc:11:22:33",
    "apFloors" : [],
    "apTags" : [],
    "observations" : [{
            "ipv4" : null,
            "location" : {
                "lat" : 5.73212614236217,
                "lng" : -5.01730431523174,
                "unc" : 1.5059361681363623,
                "x" : [],
                "y" : []
            }, 
            "seenTime" : "2015-09-30T10:59:01Z",
            "ssid" : null,
            "os" : null,
            "clientMac" : "bb:cc:dd:33:22:11",
            "seenEpoch" : 1443610741,
            "rssi" : 46,
            "ipv6" : null,
            "manufacturer" : "Hewlett-Packard"
        }
      ]
}

Upvotes: 0

Views: 1610

Answers (2)

Lior Ben Aharon
Lior Ben Aharon

Reputation: 125

You can also write:

for( var item in data.observations){
 console.log(item.bla);
}

or

for(var index=0;index<data.observations.length;index++){
 console.log(data.observations[index].bla);
}

Upvotes: 0

jfriend00
jfriend00

Reputation: 708056

data.observations is just an array of objects. There are many ways to iterate over an array. Here's one:

data.observations.forEach(function(item) {
    console.log(item.clientMac);
});

Or, if you want to create an array of them, you can do this:

var macs = data.observations.map(function(item) {
    return item.clientMac;
});
console.log(macs);     // an array of clientMac properties

You can see documentation for array.map() and array.forEach().

Upvotes: 2

Related Questions