简体   繁体   English

如何在javascript中将字符串数组转换为对象属性?

[英]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.

相关问题 如何在JavaScript中将此对象转换为数组? - How do I convert this object to an array in JavaScript? 将现有的JavaScript对象字符串属性转换为字符串数组? - Convert existing JavaScript object string property to an array of strings? 如何将数组转换为数组中的对象 - Angular和Javascript - How do I convert an array into an object within array - Angular and Javascript 如何在JavaScript中将具有属性和键的对象转换为Array? - How to convert an object with property and key to Array in JavaScript? 如何在javascript中将子数组字符串数组转换为子数组数组? - How do i convert an array of sub-array strings to an array of sub-arrays in javascript? 如何在 JavaScript 中(动态地)将对象数组转换为对象 - How do I convert an array of objects into an object (dynamically) in JavaScript 如何将多维JSON对象转换为JavaScript数组 - How do I convert a multi dimensional JSON object into javascript array 如何在 JavaScript 中将对象数组转换为一个对象? - How do I convert array of Objects into one Object in JavaScript? 如何将对象数组转换为 javascript 中的 object? - How do I convert array of objects to object in javascript? 如何将 Woocommerce 产品的嵌套数组转换为 Javascript object? - How do I convert a nested array of Woocommerce products into a Javascript object?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM