0

Given javascript object:

obj = {
    a: {
        b: {
            c: 3
           }
       }
   }

I can access the deepest property as follows: obj['a']['b']['c'] or obj.a.b.c. Now I want to access this using an array ['a', 'b', 'c']. How can I access the same object property using this array?

Note: the method does not have to "safe", so no need to check for: typeError: cannot read property ... of undefined.

Roy Prins
  • 2,510
  • 1
  • 24
  • 40

1 Answers1

4

You can do this using reduce method and pass your object as accumulator param.

const obj = {
  a: {
    b: {
      c: 3
    }
  }
}

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

function get(obj, key) {
  return key.reduce((r, e, i, a) => {
    return r[e] || (a[i + 1] ? {} : undefined)
  }, obj)
}

console.log(get(obj, key))
Kobe
  • 5,888
  • 1
  • 13
  • 35
Nenad Vracar
  • 111,264
  • 15
  • 131
  • 153