-1

I have a object like this:

const obj = {
A:{ 
  a1:'vala1', 
  a2:'vala2'
},
B:{
  b1: 'valb1',
  b2: 'valb2'
},
C:{
  c1:{
    c11:'valc11'
  },
  c2:'valc2'
}
}

An array like this const ar = ['C','c1','c11'];

How can I get the value identify by concatenation of my array keys? (obj.C.c1.c11)

Enrico
  • 27
  • 6
  • I need a solution in Typescript – Enrico Oct 19 '22 at 08:37
  • 2
    _"I need a solution in Typescript"_ -> What have you tried so far to solve this on your own? -> [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) – Andreas Oct 19 '22 at 08:41
  • In here you gotta post what you have tried and where are you stuck. That's why you're getting downvoted – Francisco Santorelli Oct 19 '22 at 08:41
  • A starting point: [Javascript: Get deep value from object by passing path to it as string](https://stackoverflow.com/questions/8817394/javascript-get-deep-value-from-object-by-passing-path-to-it-as-string) – Andreas Oct 19 '22 at 08:43

1 Answers1

1

You can use the following function and pass an object and an array of keys in order to get the corresponding value:

const obj = {
  A:{ 
    a1:'vala1', 
    a2:'vala2'
  },
  B:{
    b1: 'valb1',
    b2: 'valb2'
  },
  C:{
    c1:{
      c11:'valc11'
    },
    c2:'valc2'
  }
}

const arr: string[] = ['C','c1','c11'];

function getVal(obj, arr: string[]) {
  if ( arr.length === 1 ) {
    return obj[arr[0]];   
  }
  return getVal(obj[arr[0]], arr.slice(1));
}

console.log(getVal(obj, arr));
Fabian Strathaus
  • 3,192
  • 1
  • 4
  • 26