2

I have an object and I want to access this:

obj['example']['example-2']['example-3'];

problem is I have an array where I store those keys:

arr = ['example', 'example-2', 'example-3'];

but this array can be of variable length so maybe it's just 3 keys maybe there are 6. How can I achieve this without hardcoding each case, for example:

if(arr.length == 1){
  //obj[arr[0]];
}else if (arr.length == 2){
  //obj[arr[0]][arr[1]];
} 

etc..

3 Answers 3

1

You could use the path and reduce the object.

function getValue(o, path) {
    return path.reduce(function (o, k) {
        return (o || {})[k];
    }, o);
}

var obj = { example: { 'example-2': { 'example-3': 42 } } },
    arr = ['example', 'example-2', 'example-3'];

console.log(getValue(obj, arr));

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

Comments

1

For other people, if you didn't want to use reduce you could use a simple for loop.

function getNestedValue(obj, keys) {
  var ret = obj[keys[0]];
  for (var i = 1; i < keys.length; i++) {
    ret = ret[keys[i]];
  }
  return ret;
}

var ob = {
  HelloWorld: {
    James: {
      Ted: 55
    }
  }
};
var depth = ["HelloWorld", "James", "Ted"];

Comments

0

You could use this object-dig package :

This allows you to use method like Ruby's hash#dig in JavaScript.

var dig = require('object-dig');

var object = { a: { b: { c: 'c' } } };

dig(object, 'a', 'b');
// => { c: 'c' } 

dig(object, 'a', 'b', 'c');
// => 'c' 

dig(object, 'a', 'unknownProp', 'c');
// =>undefined 

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.