Search code examples
javascriptjavascript-objects

Dynamically access multi-level object key


I have a JavaScript object, that is multiple levels deep, for example:

let obj = [
    {
        "testKeyOne": "one",
        "testKeyTwo": "two"
    },
    {
        "testKeyThree": "three",
        "testKeyFour": "four",
        "testKeyFive": {
            "testKeyFiveAndAHalf": "5.5"
            "testKeyFiveAndThreeQuarters": "5.75"
        }
    },
]

I also have an array for the key of what I need to access, for example, if I'm looking for the 5.5 one,

let array = [1, "testKeyFive", "testKeyFiveAndAHalf"]

though my array may also look like this if I'm looking for "one"

let array = [0, "testKeyOne"]

Is there any way to use the array to access the desired value?

This is my first time asking a question so if I messed up or if there is anything unclear or something that needs to be changed I apologize.

Thank you!


Solution

  • Yep. You can just use a reduce on the array:

    let result = array.reduce((value, entry) => value[entry], obj);