[英]Appending JSON objects in Javascript
I have JSON objects being created dynamically as: 我有如下动态创建的JSON对象:
[{"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 : 我想将所有生成的所有这些对象附加到单个Javascript对象中,如下所示:
[{"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. 这样,应将每个要创建的对象附加到此JSON字符串。 I am able to concatenate two JSON objects and have it in a different Javascript variable as:
我可以连接两个JSON对象,并将其放在另一个Javascript变量中,如下所示:
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. 但是,我希望所有新生成的JSON objs都位于同一变量中。 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. 显然,对于n个对象,您将循环执行此操作,而不是如上所述。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.