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.

2
  • Maybe using recursion? Commented Apr 24, 2019 at 20:03
  • Yes, I can come up with a recursive solution but the problem seems so basic that I am afraid that I am missing something super obvious. (And I already need this as part of another recursive problem) Commented Apr 24, 2019 at 20:04

1 Answer 1

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))

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

2 Comments

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.
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 jsfiddle.net/syathrdg/3, also take a look at lodash set method.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.