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,790
  • 2
  • 28
  • 47

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
  • 6,226
  • 1
  • 14
  • 35
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
  • Im just trying to find away to access the object in this way but then also mutate that object, but I can't seem to get that to work. – Kobe Jul 04 '19 at 14:49
  • There are lots of different options based on your requirements how you want to set new value but you could start with something like this https://jsfiddle.net/syathrdg/3/, also take a look at lodash set method. – Nenad Vracar Jul 04 '19 at 15:01