Home > database >  How to get value from object using string of object path in typescript without using eval?
How to get value from object using string of object path in typescript without using eval?

Time:01-22

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
  • Related