DEV Community

Sergei
Sergei

Posted on

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

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 

Top comments (1)

Collapse
 
codelitically_incorrect profile image
codelitically_incorrect

Brilliant