0

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"
        }
      ]
}
2
  • Look up Object.keys and Array.foreach. Commented Oct 1, 2015 at 1:33
  • Why does your sample data not show .clientMac properties in it? Commented Oct 1, 2015 at 3:02

2 Answers 2

2

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().

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! The other answers are correct; however your example worked out of the box. I'm thinking I should be able to build on what you shared to also add location and timestamp data.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.