如何在JavaScript中动态获取嵌套对象属性的值?

假设我有以下对象:

let exampleObj = {
   hello: {
      there: {
         friend: 'my friend!',
         neighbor: 'neighbor!',
         world: 'world!'
      }
   }
}

有没有一种有效的方法可以创建一个函数,例如

function getPropValues(obj, ...keys) {
 // ...
}

如果我getPropValues使用以下参数调用

const result = getPropValues(exampleObj, 'hello', 'there', 'world');

它会给我的结果exampleObj['hello']['there']['world']

(即我所期望的result'world!'在这种情况下)

回答

你可以这样做

function getPropValues(obj, ...keys) {
    return keys.reduce((p, c) => {
        return p[c]
    }, obj)
}


以上是如何在JavaScript中动态获取嵌套对象属性的值?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>