1

I have an object myObj and a string myStr. I want to obtain the nested object property from the string variable alone.

How can I accomplish that?

Right now, I'm only getting undefined. I want 42.

const myObj = {
  foo: {
    bar: {
      baz: 42
}}};

const myStr = 'foo.bar.baz';

console.log('My answer: ', myObj[myStr],); // desired result: 42
Let Me Tink About It
  • 15,156
  • 21
  • 98
  • 207

1 Answers1

2

You can split on each . and use reduce to return the value from each key:

const myObj = {
  foo: {
    bar: {
      baz: 42
    }
  }
}

const myStr = 'foo.bar.baz'
const arr = myStr.split('.')
const res = arr.reduce((a, k) => a[k] || {}, myObj)

console.log('My answer:', res)

Written as a utility function:

const myObj = {
  foo: {
    bar: {
      baz: 42
    }
  }
}

const getValue = (s, o) => s.split('.').reduce((a, k) => a[k] || {}, o)

console.log('My answer:', getValue('foo.bar.baz', myObj))
Kobe
  • 6,226
  • 1
  • 14
  • 35