Fun with Array.reduce(): get a nested object by name

github logo ・1 min read

Say you have an object in the global scope such as

var level0 = {level1:{level2:{level3:'holy grail'}}};

that you want to access the last level of, and you are given its name as a string:

var nestedName = 'level0.level1.level2.level3';

There are, of course, many ways to get the value of the level3, and one way is to use Array.reduce():


var getNestedValueByName = name=>name.split('.').reduce((acc, next)=>acc[next], window);

console.log(getNestedValueByName(nestedName));
// holy grail

Also works for arrays, only have to use indices instead of names:

var a = [['first', 'second'],['third', 'fourth']];

console.log(getNestedValueByName('a.1.0'));
// third
twitter logo DISCUSS (1)
Classic DEV Post from Aug 4

You're not worth hiring unless...

Sergei profile image