假设我有这个函数签名:
export const readVariableProps = function(obj: Object, props: Array<string>) : any {
// props => ['a','b','c']
return obj['a']['b']['c'];
}
显然,props 是一个可变长度数组,具有未知列表或属性以从给定对象中读取。
是使用 eval()
获得这种动态行为的唯一方法吗?
我该怎么做?
最佳答案
获取等效于 return obj['a']['b']['c'];
where 'a'
, 'b '
和 'c'
是数组中的值,就像您在问题中显示的那样,您可以这样做(您可能需要将一些细节转换为 typeScript):
export const readVariableProps = function(obj: Object, props: Array<string>) : any {
return props.reduce(function(prior, next) {
return prior[next];
}, obj);
}
仅供引用,这种情况正是 .reduce()
的设计目的 -
累积通过访问数组中的每个项目构建的值。
如果除了数组中的最后一个属性之外的任何其他属性都不存在,这将抛出。
关于javascript - 从对象中读取可变数量的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46387643/