-1

Let's say I have object like this:

let object = {
    inner: {
        inInner: {
            a: 5
        }
    }
}

and I want to store path to property a in variable so I can access it like this:

object[pathToProperty]

Thank you for any suggestions

  • this is not possible. anyway, what have you tried? – Nina Scholz Oct 16 '19 at 08:12
  • With a single variable as a property accessor you cannot, you would need to use a [helper function](https://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-with-string-key) – Patrick Evans Oct 16 '19 at 08:14
  • in lodash lib there is a method to access nested attribute: _.get(object, pathToProperty). In your case it would be _.get(object, 'inner.inInner.a') OR, alternatively, _.get(object, ['inner', 'inInner', 'a']) – Hero Qu Oct 16 '19 at 08:19

2 Answers2

0

You can import Lodash, and use it like this:

var path = 'inner.inInner';
var value = _.get(object, path);
Max Peng
  • 2,879
  • 1
  • 26
  • 43
0

You could take a Proxy and address the inner key.

let object = { inner: { inInner: { a: 5 } } },
    proxy = new Proxy(object, {
        find: function (o, k) {
            var value;
            if (k in o) return o[k];
            Object.values(o).some(v => {
                if (v && typeof v === 'object') {
                    return value = this.find(v, k);
                }
            });
            return value;
        },
        get: function(obj, prop) {
            return prop in obj ?
                obj[prop] :
                this.find(obj, prop);
        }
    });

console.log(proxy.a);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392