Hello there im kinda new to this so what i want to do is
string = {
"string2": {
"value": ""
}
}
var path = ["string2","value"]
can i somehow get the value with the path i tried alot of things but nothing really worked
CodePudding user response:
You can use Array.reduce() for this:
const value = path.reduce((accum, key) => accum[key], string)
CodePudding user response:
You can use a loop to traverse the path step by step as follows:
const str = { "string2": { "value": "Message" } };
const path = [ "string2", "value" ];
let output = str;
path.forEach(key => {
output = output[key];
});
console.log( output );