Skip to content
Advertisement

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

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]

Advertisement

Answer

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
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement