Jquery extends json element from array

This is my original array:

var myArray = [ {"A":"1", "B":"2"}, {"C":"3", "D":"4"}, {"E":"5", "F":"6"} ] 

Then I create a copy of this myArray:

 var copyArray = $.merge([], myArray); 

And now I just want to expand the first copyArray element:

 $.extend(copyArray[0], { "Hello": "World" }); 

But as a result, both myArray and copyArray change. I just want copyArray to be changed. They are both modified below:

 [ {"A":"1", "B":"2", "Hello":"World"}, {"C":"3", "D":"4"}, {"E":"5", "F":"6"} ] 

Here is my fiddle to show this: http://jsfiddle.net/LesignButure/GFVUy/

+4
source share
5 answers

if objects exist in your array, links are saved; that is, it does not make a deep copy.

The jQuery extend method performs a deep copy when the true value is passed as the initial argument:

 $.extend(true, [], myArray ); 

JSFIDDLE

0
source
 var myArray = [ {"A":"1", "B":"2"}, {"C":"3", "D":"4"}, {"E":"5", "F":"6"} ]; var copyArray = $.extend(true, [], myArray); $.extend(copyArray[0], { "Hello": "World" }); console.log(myArray); console.log(copyArray); 

try it.

+1
source

extend does a deep copy when the true value is passed as the first argument, so you can do

 var copyArray = $.extend(true, [], myArray); 

See more details.

This solves your problem.

0
source

You can use $. extend to make a deep copy by passing true as the first parameter:

 var copyArray = $.extend(true, [], myArray); 

http://jsfiddle.net/GFVUy/12/

0
source

try it

  var copyArray = $.extend(true, [], myArray); $.extend(copyArray[0], { "Hello": "World" }); 

See DEMO

-one
source

All Articles