简体   繁体   中英

Deep Copying an array using JQuery cannot copy array of Objects

Following is my use case I have objects a , b which has the following structure

 a={arr1:[obj1={x1:1,x2:2}, obj2={x1:4,x2:4}] , arr2:[obj1={x3:55,x4:66},obj2= 
     {x3:77,x4:88}]}


 b={arr1:[obj1={x1:1,x2:2}, obj2={x1:4,x2:4},obj3={x1:44,x2:46}] , arr2:[obj1= 
     {x3:55,x4:66},obj2={x3:77,x4:88},obj1={x3:34,x4:45}]}

I want to copy the contents of a to b

I tried using b=$.extend(true,b,a)

but the contents of a are not copied in b . Object b remains unchanged. The JSON format output of b is as follows.

{"arr1":[{"x1":1,"x2":2},{"x1":4,"x2":4},{"x1":44,"x2":46}],"arr2":[{"x3":55,"x4":66},{"x3":77,"x4":88},{"x3":34,"x4":45}]}

So what is the way to copy array contents.

This way you can join a Object Array into another.

I think this is pretty straight forward. Questions? Ask me in the comments :)

 array1 = [{x:10, y:15}, {x:17, y:15}, {x:17, y:13}]; array2 = [{x:20, y:29}, {x:21, y:25}, {x:27, y:22}]; for(i=0; array1.length>i; i++){ array2.push(array1[i]); } console.log(array2); 

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