1

I have a config-file:

{
  "permission": {
    "users": {
      "image": {
        "data": "example"
      }
    }
  }
}

And an array with a called path like this:

path = ['users', 'image']

How can I get the data?

First try:

config.permission.path[0].path[1];

Second try:

switch (requestedPath[2]) {
    case 'users':
        switch (requestedPath[3]) {
            case 'image':
                mydata = config.permission.users["/image"]
        }
}

This will work, but is there a better way?

adiga
  • 34,372
  • 9
  • 61
  • 83
Janneck Lange
  • 882
  • 2
  • 11
  • 34
  • 4
    Possible duplicate of [Javascript: How to Get Object property using Array of string?](https://stackoverflow.com/questions/42863576/javascript-how-to-get-object-property-using-array-of-string) and [Accessing nested JavaScript objects with string key](https://stackoverflow.com/questions/6491463) and [Access object child properties using a dot notation string](https://stackoverflow.com/questions/8051975) – adiga Feb 25 '19 at 13:22

1 Answers1

3

You need a bracket as property accessor for the object, because you take a variable as key.

config.permission[path[0]][path[1]];

For a more dynamic approach, you could reduce the given data with a default object for not fiund properies.

const getV = (object, path) => path.reduce((result, key) => (result || {})[key], object);

var config = { permission: { users: { image: { data: 'example' } } } },
    path = ['users', 'image'];

console.log(getV(config.permission, path));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392