-2

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

omega
  • 40,311
  • 81
  • 251
  • 474
  • do you mean `"a.b.c"` or something? – jcalz Jan 21 '23 at 22:01
  • There's no built-in functionality anywhere in TS/JS that will do this so you'd have to write or import a deep indexing function (for runtime functionality) with a deep indexing type (for design time typing). As such it looks like a duplicate of [this question](https://stackoverflow.com/q/74705564/2887218) where my answer there yields the code [in this playground link](https://tsplay.dev/m0bRaw). Does that fully address your question or am I missing something? – jcalz Jan 21 '23 at 22:03

1 Answers1

-1

It I understood you question, the keys are known, if so you can use the '[]' to access it :

const a = b.c

is the same thing as

const a = b['c']

but in the second case you can of course use a variable.

Applying this to your object, it would look something like this :

const obj = {
  a: {
    b: {
      c: 1
    }
  }
}

const outerKey = 'a'
const middleKey = 'b'
const innerKey = 'c'

const value = obj[outerKey][middleKey][innerKey]

console.log(value)

Hope it helped you !

Lucasbk38
  • 499
  • 1
  • 14