2

How do I create nested elements in Javascript object through dot notation only? like

a= {};
a.b = 100; //is valid
a.x.y = 200; //is invalid?
3
  • Sorry about that, I have updated the question Commented Aug 8, 2013 at 19:56
  • Thanks! I removed the json tag. Commented Aug 8, 2013 at 19:57
  • Also, sorry if I was harsh, the intention was only to be instructive. Calling an object literal "json" is a common misconception. Commented Aug 8, 2013 at 20:00

2 Answers 2

5

The 3rd is invalid as a.x is undefined.

And you are trying to set a value to a undefined property

a= {};
a.b = 100; //is valid

a.x = {}; 
a.x.y = 200; // This works
Sign up to request clarification or add additional context in comments.

3 Comments

Yes this works, unfortunately I have to nest 7 ~ 10 objects. I can accomplish it using a["x.y....."] but it is discouraged where I work, due to some code style checks.
you can use a literal object notation like this: a = { b: 100, x: { y: 200 } }. You can nest arrays, other objects or assign functions, numbers or strings to each property. With proper indentation this way of defining a complex structure can be very clear.
@mamápitufo. That's a good way to do it, without initializing every object it the path of the object
2

You can't exactly.

a.x = {y: 200};

Comments

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.