简体   繁体   中英

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?

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:

 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:

 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM