xfbjkq
Last Updated: February 25, 2016
·
854
· joseym
Morton 066e

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.

Say Thanks
Respond

2 Responses
Add your response

13731
D42a7264714dee5006b9c99d2567a320

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 ·
13732
Morton 066e

@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 ·