0

TLDR; Is there a clever way of creating a function whos parameter can access any nested objects without having to account for hierarchy depth?

In the example below, you have a simple function returning the obj based on property. The issue arrives when function needs to access objects and or fields higher up the hierarchy. If you where to do this directly on the object, you'd simple use multiple brackets.

You could always add multiple params to the function and account for which is used, but I can't help imagine theres a better way.

Thoughts?

var obj = {parentObj: {childObj: 'hello'} }

function get(acc){
    return obj[acc];
}

console.log(get('parentObj'))                   // This of cause works.
console.log(get('parentObj.childObj'))          // But you cannot "group" multiple accessors in one variable.

console.log(obj['parentObj']['childObj']);      // If not done through generic function, you'd just do it like this.
Sulec
  • 21
  • 2

0 Answers0