2

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?

7
  • Yes, the syntax is to use more brackets or dot notation. Commented Feb 4, 2014 at 22:12
  • x['A']['B'] should do the trick Commented Feb 4, 2014 at 22:12
  • You should use x['A']['B'] or x.A.B Commented Feb 4, 2014 at 22:13
  • 1
    The situation is that I may not know exactly how many levels deep I'll need to go. I was hoping for a non-iterative way to do this. Commented Feb 4, 2014 at 22:13
  • @CoreyOgburn you'll probably want to create a method that handles the randomness of your situation. e.g.: deepProperyExists('a.b.c', obj) Just iterate over the number of periods and checking if the property is undefined each iteration. (a, a.b, a.b.c) Commented Feb 4, 2014 at 22:15

1 Answer 1

2

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.

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

4 Comments

I don't think eval is as evil as people try to say. As long as you never eval anything a user has given you.
The situation I'm thinking about is for an internal work application where the propertyPath is coming from attributes on HTML controls that way the controls can indicate what properties their values will go in to (since we're not using any data binding library). They might be properties for properties.
I updated my question with a more usable function you could use
Using info from this question about dates, this question about escaping strings, this question about testing for NaN, and your answer above. I now have getter and setter functions that retains types. JsFiddle for it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.