如何在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)
}