Reputation: 706
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?
Upvotes: 0
Views: 165
Reputation: 12018
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.
Upvotes: 1