dimanche 3 juillet 2016

Defining a nested object property in Javascript [duplicate]


I need to send a JSON object to a server which requires that the properties are nested. For example, the data object may be nested 2 levels deep. However, one cannot simply declare the object directly:

var foo = {};
foo.bar.bartwo = "data"; //Uncaught TypeError

I am currently attempting to bypass this by manually creating the nested object layer.

var foo = {};
foo.bar = {};
foo.bar.bartwo = "data"; //Successful 

However, this can quickly get out of hand if the object requires multiple levels of nesting.

Is there a better method in Javascript or Jquery to handle this issue (which does not work by simply golfing the second code example)?

Clarification: The solution should be able to allow for direct access to nested properties, without necessitating that all of the intermediate properties also be created.


Aucun commentaire:

Enregistrer un commentaire