3

I know I'm missing something obvious here but say I have a JSON object that looks like this:

testObj = {
            levelOne: {
                       levelTwo: []
            }
}

I also have a string value:

var prop = 'levelOne.levelTwo';

I'm trying to determine if there's any way to basically do something like this:

var x = testObj[prop];

That doesn't work, but is there any way to do the equivalent?

2 Answers2

5

There's no trivial way (e.g. testObj[prop]) of doing this, but the reduce function is well suited:

let nestedProp = (obj, path) =>
 path.split('.').reduce((obj, prop) => obj[prop], obj);

let x = nestedProp({levelOne: {levelTwo: [5]}}, 'levelOne.levelTwo');
console.log(x);
junvar
  • 11,151
  • 2
  • 30
  • 46
0

You can use dynamic keys to access properties in an object but not multiple levels down.

i.e. You can do const a = testObject["levelOne"] but not what you tried. (Docs)

There are however helper libs that have functions to do this. One example is lodash.get function

Special Character
  • 2,321
  • 4
  • 25
  • 34