Last Updated: August 15, 2019
·
2.967K
· joseym

Retrieve property in nested objects by Index

Lets say I have an object containing objects:

var object = { 'first': { ... }, 'second': { ... }, 'third': { ... }, 'fourth': { ... } }

I don't know the key for the third item, but I want that one.
You can grab the subobject by it's index by doing the following:

var keys = Object.keys(object) // returns all of the object property keys as an array
    , third_item = object[keys[2]]; // basically says `object.third` or `object['third']`

So that's handy, but kinda sloppy - why not "globalize" it by prototyping it to the javascript object class?

// add me to a parent javascript include!
Object.prototype.byIndex = function(index) {
  var keys = Object.keys(this);
  return this[keys[index]];
};

Now you could simply do object.byIndex(2).

Javascript is magic.

2 Responses
Add your response

The order of object keys is not guaranteed and you shouldn't rely on it. See
http://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order

over 1 year ago ·

@dpashkevic - I'm aware. This is most useful in a situation where the order doesn't matter, you just need to grab an object at X, but dont know the key used for X.

over 1 year ago ·