Last Updated: February 25, 2016
· 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

2 Responses
Add your response


The order of object keys is not guaranteed and you shouldn't rely on it. See

over 1 year ago ·
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 ·