Mark Mark - 5 months ago 15
Javascript Question

Using JSON Object Name if Object name is a number

I am using an API that returns an array of data, which I JSON.Parse in order to use the data. I am able to gather the proper data details, however I want to be able to link those details to the object which they are contained in.

I use the following code to gather my array and JSON parse:

var venue = JSON.parse(this.responseText);
console.log(venue);


which returns:
Object {4293315: Array[108]}


I then parse through the array contained in '4293315' by running the following code:

for(var person in venue) {
var personDetail = venue[person];

for(detail in personDetail) {
if(personDetail[detail].max_rssi > maxRssi) {
venueDetails.push(personDetail[detail]);
}
}
}

var capacity = venueDetails.length;
capacity --;
console.log("capacity: " + capacity);
var temp = JSON.stringify(venueDetails);
console.log(venue +": " + temp);


which returns:

capacity: 6
[object Object]: [{"mac_id":12960837,"wifi_uid":null,"first_seen":"2016-06-14T00:13:23.000Z","last_seen":"2016-06-14T00:13:23.000Z","max_rssi":-55,"latest_rssi":-55,"frames":1},...


The issue is that the object name is an id number, for example
4293315
, so I receive an error when I try to run
venue.4293315.name
.

Can someone please help me figure out how to store the object name so that I can associate the values contained inside with the object? For example, I want to be able to store the object name in a key and value map, so that I can later ask for the capacity information of each object or ID.

Answer

You can programmatically get the value of the name by doing:

var objectNames = Object.keys(venue); // gives an array of the keys

Assuming you know there is only one:

var id = objectNames[0];

Then you can access the properties using id as others have shown.