简体   繁体   中英

Appending JSON objects in Javascript

I have JSON objects being created dynamically as:

[{"fill":"none","stroke":"#000000","path":"M186.5,25L187.5,25L187.5,26L188.5,27L189.5,28L189.5,29L190.5,29","stroke-opacity":1,"stroke-width":5,"stroke-linecap":"round","stroke-linejoin":"round","transform":[],"type":"path"}]

[{"fill":"none","stroke":"#000000","path":"M73.5,42L73.5,42L75.5,43L82.5,46L101.5,55L119.5,65L126.5,69L128.5,71L129.5,71","stroke-opacity":1,"stroke-width":5,"stroke-linecap":"round","stroke-linejoin":"round","transform":[],"type":"path"}]

.......

I want to append all these Objects being generated into a single Javascript object as :

[{"fill":"none","stroke":"#000000","path":"M186.5,25L187.5,25L187.5,26L188.5,27L189.5,28L189.5,29L190.5,29","stroke-opacity":1,"stroke-width":5,"stroke-linecap":"round","stroke-linejoin":"round","transform":[],"type":"path"},
{"fill":"none","stroke":"#000000","path":"M73.5,42L73.5,42L75.5,43L82.5,46L101.5,55L119.5,65L126.5,69L128.5,71L129.5,71","stroke-opacity":1,"stroke-width":5,"stroke-linecap":"round","stroke-linejoin":"round","transform":[],"type":"path"}]

In this way every object being created should be appended to this JSON string. I am able to concatenate two JSON objects and have it in a different Javascript variable as:

var obj1 = '[{"fill":"none","stroke":"#000000","path":"M186.5,25L187.5,25L187.5,26L188.5,27L189.5,28L189.5,29L190.5,29","stroke-opacity":1,"stroke-width":5,"stroke-linecap":"round","stroke-linejoin":"round","transform":[],"type":"path"}]';

var obj2 = '[{"fill":"none","stroke":"#000000","path":"M186.5,25L187.5,25L187.5,26L188.5,27L189.5,28L189.5,29L190.5,29","stroke-opacity":1,"stroke-width":5,"stroke-linecap":"round","stroke-linejoin":"round","transform":[],"type":"path"}]';

var mergedJS = JSON.parse(obj1).concat(JSON.parse(obj2));

  mergedJSON =JSON.stringify(mergedJS);

I however, want all the newly generated JSON objs in the same variable. Could anyone please let me know how can I do this?

You'll need to pull the objects out of their individual arrays before adding them to the master array:

var newJSArray = [];
var mergedJS = JSON.parse(obj1);
newJSArray.push(mergedJS[0]);
mergedJS = JSON.parse(obj2);
newJSArray.push(mergedJS[0]);

Obviously for n objects you'll be looping that instead of as I've done above.

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