如何仅从JS中的字符串变量获取嵌套对象属性?

时间:2019-08-15 08:49:09

标签: javascript

我有一个对象myObj和一个字符串myStr。我想仅从字符串变量中获取嵌套对象属性。

我该怎么做?

现在,我只得到undefined。我要42

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

const myStr = 'foo.bar.baz';

console.log('My answer: ', myObj[myStr],); // desired result: 42

1 个答案:

答案 0 :(得分:2)

您可以分割每个.并使用reduce从每个键返回值:

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)

写为实用函数:

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))