从对象中读取可变数量的属性

时间:2017-09-24 07:24:58

标签: javascript node.js dynamic

说我有这个功能签名:

export const readVariableProps = function(obj: Object, props: Array<string>) : any {

   // props => ['a','b','c']
   return obj['a']['b']['c'];

}

很明显,props是一个可变长度的数组,有一个未知的列表或属性可以从给定的对象中读取。

是使这种动态行为使用eval()的唯一方法吗?

我该怎么做?

2 个答案:

答案 0 :(得分:1)

要获得等同于return obj['a']['b']['c'];,其中'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()的设计目标 - 累积通过访问数组中的每个项目而构建的值。

如果数组中的最后一个属性不存在,则抛出此内容。

答案 1 :(得分:1)

您可以使用for..of循环为每个嵌套属性设置变量

&#13;
&#13;
const props = ['a','b','c'];
const obj = {a:{b:{c:123}}};

let res;
for (let prop of props) res = !res ? obj[prop] : res[prop];

console.log(res);
&#13;
&#13;
&#13;

相关问题