views:

87

answers:

2

For example, I have the following JSON object json_obj1

json_obj1 = {x:{id:1,bars:{show:true,barWidth:0.4}}}

Now, how could I add the following object (using javascript):

   y:{id:2,bars:{show:true,barWidth:0.4}}

to json_obj1 so that it will be:

{x:{id:1,bars:{show:true,barWidth:0.4}},y:{id:2,bars:{show:true,barWidth:0.4}}}
+4  A: 

You can just set the field y of your json_obj1

json_obj1 = {x:{id:1,bars:{show:true,barWidth:0.4}}}
json_obj1.y = {id:2,bars:{show:true,barWidth:0.4}}

Now json_obj1 = {x:{id:1,bars:{show:true,barWidth:0.4}},y:{id:2,bars:{show:true,barWidth:0.4}}}

goatlinks
+1  A: 

It doesn't appear as if your question actually involves JSON. The first code fragment is just a JavaScript object literal. Given your description of the problem, something like this should work:

json_obj1 = {x:{id:1,bars:{show:true,barWidth:0.4}}};
json_obj1.y = {id:2,bars:{show:true,barWidth:0.4}};

This will give you the desired contents in json_obj1;

Mark Bessey
+1 for pointing out that the question doesn't involve JSON.
Tim Down