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
You can use Array.reduce() for this:
const value = path.reduce((accum, key) => accum[key], string)
There are several approaches. First, you can use a loop to traverse the path step by step as follows:
const obj = { "string2": { "value": "Message" } };
const path = [ "string2", "value" ];
let output = obj;
path.forEach(key => {
output = output[key];
});
console.log( output );
RECURSION
const obj = { "string2": { "value": "Message" } };
const path = [ "string2", "value" ];
const trav = (o,p,i) => (i < p.length - 1) ? trav(o[p[i]],p,i+1) : o[p[i]];
console.log( trav(obj,path,0) );
new Function
const obj = { "string2": { "value": "Message" } };
const path = [ "string2", "value" ];
const output = (new Function(`return (obj.${path.join('.')})`))();
console.log( output );