简体   繁体   中英

javascript manipulate json object

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}}}

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}}}

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM