In JS/typescript, lets say I have an object like this
var obj = {
a: {
b:{
c:1
}
}
}
And I have a string "b.c"
. How can I evaluate this using only those variables and get the value 1
from the object without using hacks like eval
since typescript would complain.
Thanks
CodePudding user response:
You can use the reduce method to achieve this.
const getValueFromObjectPath = (obj, path) => {
return path.split('.').reduce((prev, curr) => prev ? prev[curr] : undefined, obj);
}
getValueFromObjectPath(obj, 'a.b.c') // 1