Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference nested json object property by string [duplicate]

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?

like image 885
monkeyWithAMachinegun Avatar asked Oct 29 '25 13:10

monkeyWithAMachinegun


1 Answers

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);
like image 104
junvar Avatar answered Nov 01 '25 02:11

junvar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!