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

Classic DEV Post from 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!