Corey Ogburn
Corey Ogburn

Reputation: 24769

Property of property using String in brackets?

Let's say I have a complex object with properties that have properties.

var x = {};
x.A.B = 'Hello';
x.A.C = 'World!';
x.D.E = 100;
x.D.F = 2.5;

Is there anything I could put in a single set of square brackets in order to get back any of these properties? A simple test shows that x['A.B'] does not return 'Hello'. Is there any syntax for doing this?

Upvotes: 2

Views: 152

Answers (1)

Bart
Bart

Reputation: 17371

If you don't want to iterate you could do it fairly safe with eval in strict mode. Not that I recommend doing this. But it's a way to do it.

var x = {A:{}};
x.A.B = 'Hello';

var propertyPath = 'A.B';
var value = eval('"use strict"; x.' + propertyPath);

console.log(value);

Another more reusable way would be to create a new Function object instead of using eval.

function propertyValue(obj, propertyPath) {
    'use strict';
    return (new Function('obj', 'return obj.' + propertyPath))(obj);
}

var value = propertyValue(x, 'A.B');

It is practically the same but has a clear definition.

Upvotes: 2

Related Questions