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.

2
  • 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? Commented Oct 9, 2018 at 3:20
  • Possible duplicate of How to use an array of keys to fetch the value from a Javascript object Commented Oct 9, 2018 at 3:28

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.