4

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?

0

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant, thanks - I knew there had to be a simple way to do this. This gives me exactly what I was looking for.
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.