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?

1

1 Answer 1

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.