Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access property of nested object given dynamic keys?

Tags:

javascript

I have a nested object of which I do not know the structure of. For example:

const nestedObject = {
  "one": {
    "two": {
       "three": 3
     }
  }
}

I wanted to display value of three.

I have an array like this so that I know how to navigate the object in order to get to three:

const keys = ["one", "two", "three"]

This doesn't have to be structured this way.

So how do I access one.two.three given the keys array above? Or some other data structure. I was thinking of doing a recursion, but it seems too complex and I feel like there is a simple solution out there.

like image 952
jeanl Avatar asked Oct 17 '25 09:10

jeanl


1 Answers

You can do it with a simple Array.prototype.reduce() function:

const data = {
  "one": {
    "two": {
       "three": 3
     }
  }
};

const keys = ["one", "two", "three"];

const value = keys.reduce((a, v) => a[v], data);

console.log(value);
like image 86
Robby Cornelissen Avatar answered Oct 18 '25 21:10

Robby Cornelissen