How can I access object properties using an array of strings / keys?

Viewed 31

Let us consider the following array and object:

const keys = ['a', 'b', 'c'];

const object = {
  a: {
    b: {
      c: {
        data: 1
      }
    }
  }
}

Naturally, I would access the data like so:

object['a']['b']['c']

The question is, how can I access the data using the array as input? Something like:

object[...keys]
2 Answers

Probably no other way to do this

const keys = ['a', 'b', 'c'];

const object = {
  a: {
    b: {
      c: {
        data: 1
      }
    }
  }
}

console.log(getValue(object, ...keys))

function getValue(obj, ...keys) {
  let current = obj
  for (const key of keys) {
    current = current[key]
  }
  return current
}

You can loop through the keys:

function getValueAtObjectPath(obj, path) {
  let val = obj;
  let key = path.shift();
  while(key && val) {
    val = val[key];
    key = path.shift();
  };
  return val;
}

const keys = ['a', 'b', 'c'];

const object = {
  a: {
    b: {
      c: {
        data: 1
      }
    }
  }
}

let val = getValueAtObjectPath(object, keys);
console.log('value at object path: ' + JSON.stringify(val));

Return:

value at object path: {"data":1}
Related