Rich
Rich

Reputation: 133

Javascript: how do I access a key in a dynamically-named nested object?

Here's my situation: I'm working with an array that has a bunch of nested objects. One of those nested objects has a name that changes dynamically. How can I consistently access a key of one of it's child objects?

Here's a few examples of the paths that it can have:

kml[id].overlayData._layers.136._bounds._northEast.lat
kml[id].overlayData._layers.143._bounds._northEast.lat
kml[id].overlayData._layers.82._bounds._northEast.lat
kml[id].overlayData._layers.87._bounds._northEast.lat
kml[id].overlayData._layers.76._bounds._northEast.lat

The child object that I'm trying to access is 'lat', which has a couple of keys within it.

Apologies for any weird / incorrect use of terminology, I'm still trying to get my head around concepts like this.

Upvotes: 1

Views: 59

Answers (3)

kevin ternet
kevin ternet

Reputation: 4612

You can loop thanks to for..in loop

for (var prop in kml[id].overlayData._layers) 
   console.log(kml[id].overlayData._layers[prop]._bounds._northEast.lat);

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386570

You could get the key with Object.keys.

var keys = Object.keys(kml[id].overlayData._layers);

// access
keys.forEach(function (key) {
    // kml[id].overlayData._layers[key]._bounds._northEast.lat
});

For only one unknown key, you could use directly the first element of the keys array

var key = Object.keys(kml[id].overlayData._layers)[0];

// access with
kml[id].overlayData._layers[key]._bounds._northEast.lat

Upvotes: 1

Feathercrown
Feathercrown

Reputation: 2591

Try this, if I understand the question correctly:

var number = 354; //whatever number you want to get the value from
kml[id].overlayData._layers['number']._bounds._northEast.lat

Note that you can't use blahblah.123 to access a number-started property; use blahblah['123'] instead. This also allows you to pass in variables, like the example above.

Upvotes: 0

Related Questions