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

说我有这个function签名:

export const readVariableProps = function(obj: Object, props: Array<string>) : any { // props => ['a','b','c'] return obj['a']['b']['c']; } 

显然,道具是一个可变长度的数组,具有未知的列表或属性来从给定的对象读取。

是获得这种dynamic行为使用eval()的唯一方法?

我怎样才能做到这一点?

得到相当于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); } 

仅供参考,这种types的场景正是为.reduce()devise的 – 积累通过访问数组中的每个项目而构build的值。

如果除数组中最后一个属性以外的任何内容不存在,则会抛出。

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

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