1

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.

March Ho
  • 420
  • 9
  • 21
  • 4
    `var foo = {bar: {bartwo: "data"}};` – naththedeveloper Jun 22 '16 at 13:10
  • create simple "namespace" function. or google one – dfsq Jun 22 '16 at 13:10
  • @naththedeveloper While your solution is more concise, it doesn't actually solve the root problem. The nesting may require multiple levels to be generated dynamically, which would not work with your example. – March Ho Jun 22 '16 at 13:11
  • What you're asking is impossible because to add a property to an object, the object must exist. The best you can do is make a function that lessens the burden of doing so, like [this one](http://stackoverflow.com/a/11433067/5743988). – 4castle Jun 22 '16 at 13:18
  • var foo['bar'] = {'a': 'b'} You can do something like this – Hassan Abbas Jun 22 '16 at 13:19

2 Answers2

0

without defining nested object i.e foo.bar = {}; you can not use or assign value to it javascript object must be defined first to use it otherwise it will give you 'undefined' error i.e foo.bar is undefined

Akash
  • 11
  • 3
0

create a small method that does this

function nested(x, y){
nestedA="";
parts = x.split('.');
  for(i=0; i<parts.length; i++) {
    nestedA += parts[i];
    eval(nestedA + ' = {}');
    nestedA += '.';
}
eval(nestedA.slice(0,-1)+ '= "'+y+'"');
}
nested('foo.bar.bartwo', "data");
Yehuda Schwartz
  • 3,378
  • 3
  • 29
  • 38