0

Imagine I have an array, which looks like:

const x = ["a", "b", "c", "d"]

I wish to use it in order to navigate an object that I don't know the structure of, like:

const y = {
    "a": {
        "b": {
            "c": {
                "d": "Value I require"
            }
        },
        "f": ["g", "h"]
    },
    "e": null
}

However, my issue is that I don't know how deep y will be, or how many indices are in the array x. How do I do the following:

let someVariable = {"prefilled": "data"}
someVariable[x[0]][x[1]][x[2]][x[3]] = y[x[0]][x[1]][x[2]][x[3]]

In a way which is neither specific to the length of x, the depth of y (and also preferably isn't my current solution, which is a case statement upto a depth of 6)? For this simplified case, someVariable should hopefully look as follows:

{
    "prefilled": "data",
    "a": {
        "b": {
            "c": {
                "d": "Value I require"
            }
        }
    }
}
Alexander Craggs
  • 7,874
  • 4
  • 24
  • 46
  • Also a duplicate of [Accessing nested JavaScript objects with string key](http://stackoverflow.com/q/6491463/218196) – Felix Kling Jan 02 '17 at 18:44
  • @FelixKling Damnit, sorry about the duplicate. I guess I just couldn't phrase the question in the right way for Google ;). – Alexander Craggs Jan 02 '17 at 18:47
  • No worries, searching can be difficult :) I guess that's an even better one: [How to set object property (of object property of..) given its string name in JavaScript?](http://stackoverflow.com/q/13719593/218196) – Felix Kling Jan 02 '17 at 18:48

2 Answers2

1

I would either use a tool like Lodash's _.get or implement something similar that can navigate an object:

let _ = require('lodash');
const x = ["a", "b", "c", "d"]
_.get(object, x.join('.'))
Nick Tomlin
  • 28,402
  • 11
  • 61
  • 90
  • A great answer! Especially considering I actually get my data in the format of "a.b.c.d" and turned it into an array for convenience. Allows me to also do `_.set` to set the other object instance, as a note to future readers. – Alexander Craggs Jan 02 '17 at 18:25
1

You could iterate the array and walk the object.

const getValue = (object, path) => path.reduce((o, k) => (o || {})[k], object),
      y = { a: { b: { c: { d: "Value I require" } }, f: ["g", "h"] }, e: null },
      x = ["a", "b", "c", "d"]

console.log(getValue(y, x));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392