[英]How do I convert an array of strings to an object property in javascript?
What is the best way to convert an array of strings to access an objects property? 转换字符串数组以访问对象属性的最佳方法是什么?
For example: 例如:
var obj = {
a: {
b: {
c: 4
}
}
};
I have an array 我有一个阵列
var arr = ['a', 'b', 'c'];
What is the most efficient to iterate through the array to get 4 with just accessing obj? 只需访问obj,迭代数组获得4的效率最高是什么?
This is with not knowing how many dimensions the object has. 这是因为不知道对象有多少维度。
Use reduce
, accessing the [prop]
of the current accumulator object each time, passing in the obj
as the initial value: 使用
reduce
,每次访问当前累加器对象的[prop]
,传递obj
作为初始值:
var obj = { a: { b: { c: 4 } } }; var arr = ['a', 'b', 'c']; console.log( arr.reduce((a, prop) => a[prop], obj) );
For ES5, just turn the arrow function into a standard function: 对于ES5,只需将箭头功能转换为标准功能:
var obj = { a: { b: { c: 4 } } }; var arr = ['a', 'b', 'c']; console.log( arr.reduce(function(a, prop) { return a[prop]; }, obj) );
That said, it's far better to write in the latest and greatest version of the language and, if you need to support ancient browsers, use Babel later to automatically transpile your code down to ES5 during your build step. 也就是说,用最新最好的语言编写它会好得多,如果你需要支持古老的浏览器,可以在以后使用Babel在构建步骤中自动将代码转换为ES5。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.