3

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.

KingKongFrog
  • 13,946
  • 21
  • 75
  • 124
  • Some algorithms solve this case with same output, but generate different outputs for other inputs. It would be better you extend you example of the input, such as, what your expected output for siblings keys. Each key is one level? – Andre Figueiredo Oct 09 '18 at 03:20
  • Possible duplicate of [How to use an array of keys to fetch the value from a Javascript object](https://stackoverflow.com/questions/46994085/how-to-use-an-array-of-keys-to-fetch-the-value-from-a-javascript-object) – Andre Figueiredo Oct 09 '18 at 03:28

1 Answers1

6

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.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320