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.
Written by Josey Morton
Related protips
2 Responses
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
@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.
Have a fresh tip? Share with Coderwall community!
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside