MyTetra Share
Делитесь знаниями!
How do you clone an Array of Objects in Javascript?
Время создания: 13.07.2018 15:30
Текстовые метки: javascript clone array
Раздел: Javascript

...where each object also has references to other objects within the same array?


When I first came up with this problem I just though of something like


var clonedNodesArray = nodesArray.clone()

would exist and searched for info on how to clone objects in javascript. I did find a question on StackOverflow (answered by the very same @JohnResig) and he pointed out that with jQuery you could do


var clonedNodesArray = jQuery.extend({}, nodesArray);

to clone an object. I tried this though, this only copies the references of the objects in the array. So if I


nodesArray[0].value = "red"

clonedNodesArray[0].value = "green"

the value of both nodesArray[0] and clonedNodesArray[0] will turn out to be "green". Then I tried


var clonedNodesArray = jQuery.extend(true, {}, nodesArray);

which deep copies an Object, but I got "too much recursion" and "control stack overflow" messages from both Firebug and Opera Dragonfly respectively.


How would you do it? Is this something that shouldn't even be done? Is there a reusable way of doing this in Javascript?


javascript

shareimprove this question

edited May 23 '17 at 11:47


Community♦

11

asked Feb 28 '09 at 5:56


wallyqs

2,40531922

add a comment

29 Answers

active oldest votes

up vote

78

down vote

accepted

The issue with your shallow copy is that all the objects aren't cloned. While the references to each object are unique in each array, once you ultimately grab onto it you're dealing with the same object as before. There is nothing wrong with the way you cloned it... the same result would occur using Array.slice().


The reason your deep copy is having problems is because you're ending up with circular object references. Deep will go as deep as it can go, and if you've got a circle, it'll keep going infinitely until the browser faints.


If the data structure cannot be represented as a directed acyclic graph, then I'm not sure you're going to be able to find an all-purpose method for deep cloning. Cyclic graphs provide many tricky corner cases, and since it's not a common operation I doubt anyone has written a full solution (if it's even possible - it might not be! But I have no time to try to write a rigorous proof now.). I found some good comments on the issue on this page.


If you need a deep copy of an Array of Objects with circular references I believe you're going to have to code your own method to handle your specialized data structure, such that it is a multi-pass clone:


On round one, make a clone of all objects that don't reference other objects in the array. Keep a track of each object's origins.

On round two, link the objects together.

shareimprove this answer

edited Feb 28 '09 at 8:12

answered Feb 28 '09 at 8:04


Daniel Lew

64.2k25161167

2

I have an error on your link. – Elfayer Jun 27 '14 at 8:29

1

Fixed link for @PatrickdeKleijn answer: web.archive.org/web/20140222022056/http://my.opera.com/… – Mike Szyndel Dec 8 '15 at 17:25

add a comment

up vote

370

down vote

C'mon guys, it is the 21st century: as long as your objects contain JSON-serializable content (no functions, no Number.POSITIVE_INFINITY, etc.) there is no need for any loops to clone arrays or objects. Here is a pure vanilla one-line solution.


var clonedArray = JSON.parse(JSON.stringify(nodesArray))

To summarize the comments below, the primary advantage of this approach is that it also clones the contents of the array, not just the array itself. The primary downsides are its limit of only working on JSON-serializable content, and it's performance (which is significantly worse than a slice based approach).


shareimprove this answer

edited May 3 '17 at 0:30


machineghost

16.8k1881148

answered May 5 '14 at 20:19


Vladimir Kharlampidi

4,9382910

72

This might work for JSON data, but if your array contains any functions or instances of objects that have methods, say goodbye to them. – sp0rkyd0rky Oct 23 '14 at 1:43

7

be careful if you have an array which contains the value Infinity. This value gets lost (is null afterwards). (jsfiddle.net/klickagent/ehm4bd3s) – klickagent.ch Feb 1 '15 at 16:16

9

This is just generally a bad approach unless your array contains only primitives, and/or objects which themselves contain only string/number/boolean primitives (even null and undefined will be problems, since JSON doesn't support them). Further, it's a vastly less efficient operation than old_array.slice(0);, which should work both better and faster. – XML Sep 7 '15 at 9:38

1

if object of array has DateTime, then string will be returned instead of DateTime! new Date !== JSON.parse(JSON.stringify(new Date)) – MarkosyanArtur Jan 15 '16 at 7:41

2

The key line in the OP's question, which this answer above ignores entirely: ...where each object also has references to other objects within the same array? – XML Mar 14 '17 at 4:35

show 7 more comments

up vote

164

down vote

If all you need is a shallow copy, a really easy way is:


new_array = old_array.slice(0);

shareimprove this answer

answered Nov 9 '10 at 18:05


Leopd

24.5k24102147

4

I don't think you have to pass 0, you can just call .slice() at least in chrome anyway – slf Apr 23 '13 at 17:51

78

This doesn't actually work though, does it? I mean, it's not an answer to the question how to clone an array of objects. This is the solution to clone a simple array. – bozdoz Dec 30 '13 at 23:17

22

Actually this won't work for an objects array. The returned array by slice will be a new array but will contain the references to the original array objects. – Sergio A. Mar 7 '14 at 21:51

4

This will work only for "generics" int, string etc. but not for an array of objects. – Stefan Michev Nov 19 '14 at 17:09

3

for array of objects this doesn't actually clone, update to the new_array will also update the old_array . – Anas Mar 30 '16 at 15:28

show 1 more comment

up vote

152

down vote

I solved cloning of an array of objects with Object.assign


const newArray = myArray.map(a => Object.assign({}, a));


or even shorter with spread syntax


const newArray = myArray.map(a => ({...a}));


shareimprove this answer

edited Sep 13 '17 at 22:50

answered Oct 27 '16 at 11:16


dinodsaurus

2,25631423

9

But if myArray contained a bunch of Dinosaurs, newArray contains a bunch of Objects. That's lame, don't you agree? – Matthew James Davis Mar 27 '17 at 20:09

2

best approach, as it keeps objects functions alive, rathen then losing them with JSON.parse(JSON.stringify(nodesArray)) – scipper Sep 8 '17 at 13:30

no problem at all – Manos Kounelakis Sep 14 '17 at 11:11

This should be the accepted answer imho – LeandroG Apr 28 at 1:00

1

@MatthewJamesDavis you can solve this by replacing {} with new Dinosaur(). – Agargara Jun 6 at 8:32

add a comment

up vote

32

down vote

Best and most up to date way to do this clone is as follows:


Using the "..." ES6 spread operator.


Here's the most simple Example:


var clonedObjArray = [...oldObjArray];

This way we spread the array into individual values and put it in a new array with the [] operator.


Here's a longer example that shows the different ways it works:


let objArray = [ {a:1} , {b:2} ];


let refArray = objArray; // this will just point to the objArray

let clonedArray = [...objArray]; // will clone the array


console.log( "before:" );

console.log( "obj array" , objArray );

console.log( "ref array" , refArray );

console.log( "cloned array" , clonedArray );


objArray[0] = {c:3};


console.log( "after:" );

console.log( "obj array" , objArray ); // [ {c:3} , {b:2} ]

console.log( "ref array" , refArray ); // [ {c:3} , {b:2} ]

console.log( "cloned array" , clonedArray ); // [ {a:1} , {b:2} ]

Run code snippetExpand snippet

shareimprove this answer

edited Aug 13 '17 at 15:05

answered Jan 3 '17 at 9:03


MennyMT

961715

2

Good modern answer, that won't work with older browsers (like IE 11) – Jealie Feb 20 '17 at 20:00

1

@Jealie I'm going to guess KingpinEX is targeting this answer for folks transpiling es6 to something more universally useful with Babel or what have you. – ruffin Apr 6 '17 at 21:21

11

This just deep copies the array, not each object in the array. – Toivo Säwén Jul 18 '17 at 8:52

This doesn't work – userqwert Oct 20 '17 at 14:25

8

To follow up on what @ToivoSäwén said, this will not deep copy the objects in the array. It will still reference the original objects so if you mutate them, it will impact the original array as well. – jkinz Nov 16 '17 at 23:39

show 2 more comments

up vote

31

down vote

Simply clone any type of array with:


[].concat(data);

or, since concat may not work in some IE browsers, you can use this:


data.slice(0);

shareimprove this answer

edited Nov 20 '12 at 11:49

answered Oct 22 '12 at 23:37


SET

7,44242954

35

Neither of these will clone the objects, but simply create new arrays referencing the original objects. – Pappa Oct 27 '15 at 11:03

add a comment

up vote

25

down vote

This works for me:


var clonedArray = $.map(originalArray, function (obj) {

return $.extend({}, obj);

});

And if you need deep copy of objects in array:


var clonedArray = $.map(originalArray, function (obj) {

return $.extend(true, {}, obj);

});

shareimprove this answer

answered Jun 22 '12 at 18:41


viliks

31935

1

This looks like it would work. I'm trying to avoid extensive jQuery use, so I won't use it in my situation, but a for loop and for...in would work. – bozdoz Dec 30 '13 at 23:24

This is great for a two-level deep copy. Thanks for posting. – Andrew Mao Jan 29 '14 at 20:11

add a comment

up vote

18

down vote

$.evalJSON($.toJSON(origArray));

shareimprove this answer

edited Sep 7 '11 at 2:19


alex

324k157745897

answered Aug 4 '10 at 20:00


elsereturn

22122

2

You will need to be using the jquery json plugin to use this code.google.com/p/jquery-json – wmitchell Aug 4 '11 at 15:00

30

Without JQ (fine in modern browsers): JSON.parse(JSON.stringify(origArray)); – forresto May 27 '13 at 12:10

I found this comment useful. In my implementation I needed to make a copy of an array of objects that had KnockoutJS observable properties applied. The copy only needed the values, not the observable-ness. To make a copy of JUST the values I used JSON.parse(ko.toJSON(origArray)) OR ko.utils.parseJson(ko.toJSON(origArray)). Just my 2 cents and thank you for helping me arrive at my solution. – wavedrop Aug 23 '13 at 15:29

5

JSON.parse(JSON.stringify(origArray)); is definitely the simplest solution. – yorkw Sep 23 '13 at 21:43

JSON.parse(JSON.stringify(origArray)); works! – Konrad Jul 23 '15 at 14:23

add a comment

up vote

8

down vote

I may have a simple way to do this without having to do painful recursion and not knowing all the finer details of the object in question. Using jQuery, simply convert your object to JSON using the jQuery $.toJSON(myObjectArray), then take your JSON string and evaluate it back to an object. BAM! Done, and done! Problem solved. :)


var oldObjArray = [{ Something: 'blah', Cool: true }];

var newObjArray = eval($.toJSON(oldObjArray));

shareimprove this answer

edited Sep 7 '11 at 2:44


Yi Jiang

40.5k13120125

answered May 31 '10 at 8:23


George

8911

20

Some modern browsers have the JSON method built-in so you can do this: JSON.parse(JSON.stringify(MY_ARRAY)) which should be faster. Good suggestion. – Nicolas R Jun 18 '10 at 14:07

1

And if they don't use json2, not eval. – kamranicus Jan 9 '12 at 18:02

This has terrible performance, but unfortunately is the best answer I've seen :/ – Dvid Silva Jun 25 '14 at 20:13

add a comment

up vote

8

down vote

I'm answering this question because there doesn't seem to be a simple and explicit solution to the problem of "cloning an array of objects in Javascript":


function deepCopy (arr) {

var out = [];

for (var i = 0, len = arr.length; i < len; i++) {

var item = arr[i];

var obj = {};

for (var k in item) {

obj[k] = item[k];

}

out.push(obj);

}

return out;

}


// test case


var original = [

{'a' : 1},

{'b' : 2}

];


var copy = deepCopy(original);


// change value in copy

copy[0]['a'] = 'not 1';


// original[0]['a'] still equals 1

This solution iterates the array values, then iterates the object keys, saving the latter to a new object, and then pushing that new object to a new array.


See jsfiddle. Note: a simple .slice() or [].concat() isn't enough for the objects within the array.


shareimprove this answer

answered Dec 30 '13 at 23:59


bozdoz

7,17163771

thanks for the answer, but you should've highlighted the shortcomings of the answer. It doesn't work when the objects have objects in it.. right? – Harsh Mar 19 '17 at 5:38

Doesn't work with objects within objects, no. – bozdoz Mar 19 '17 at 6:26

add a comment

up vote

6

down vote

JQuery extend is working fine, just you need to specify that you are cloning an array rather than an object (note the [] instead of {} as parameter to the extend method):


var clonedNodesArray = jQuery.extend([], nodesArray);

shareimprove this answer

edited Mar 26 '14 at 6:12

answered Dec 20 '12 at 8:33


Stef

1,3801023

2

Hmm, if you downvote this, can you please add a comment about why you do so? Or can you first try the code and see if it works or not? Thanks ;) – Stef Mar 16 '16 at 4:35

1

After changing an object in first array, the object in second array gets modified, so it's not ok. – Spikolynn Oct 25 '17 at 7:42

add a comment

up vote

5

down vote

As Daniel Lew mentioned, cyclic graphs have some problems. If I had this problem I'd either add special clone() methods to the problematic objects or remember which objects I've already copied.


I'd do it with a variable copyCount which increases by 1 every time you copy in your code. An object that has a lower copyCount than the current copy-process is copied. If not, the copy, that exists already, should be referenced. This makes it necessary to link from the original to its copy.


There is still one problem: Memory. If you have this reference from one object to the other, it's likely that the browser can't free those objects, as they are always referenced from somewhere. You'd have to make a second pass where you set all copy-references to Null. (If you do this, you'd not have to have a copyCount but a boolean isCopied would be enough, as you can reset the value in the second pass.)


shareimprove this answer

answered Feb 28 '09 at 8:53


Georg Schölly

94.8k41179241

add a comment

up vote

4

down vote

Array.slice can be used to copy an array or part of an array.. http://www.devguru.com/Technologies/Ecmascript/Quickref/Slice.html This would work with strings and numbers .. - changing a string in one array would not affect the other - but objects are still just copied by reference so changes to referenced objects in one array would have an affect on the other array.


Here is an example of a JavaScript undo manager that could be useful for this :http://www.ridgway.co.za/archive/2007/11/07/simple-javascript-undo-manager-for-dtos.aspx


shareimprove this answer

edited Feb 28 '09 at 7:45

answered Feb 28 '09 at 7:07


markt

4,4902124

I know. The reason I wanted to implement this is because I'm trying to resolve a CSP problem with backtracking. I thought that one of the ways of implementing backtracking could be like "taking snapshots" the state of the assignment of the variables by... cloning such snapshots into a stack. – wallyqs Feb 28 '09 at 7:32

...and well, it might actually be a very bad idea. – wallyqs Feb 28 '09 at 7:33

That approach could have other synchronization complications :).. How do you know the array is not being changed while you are taking a snapshot? – markt Feb 28 '09 at 7:38

Added a link to an article where the author implemented a simple undo manager using javascript.. – markt Feb 28 '09 at 7:46

add a comment

up vote

4

down vote

My approach:


var temp = { arr : originalArray };

var obj = $.extend(true, {}, temp);

return obj.arr;

gives me a nice, clean, deep clone of the original array - with none of the objects referenced back to the original :-)


shareimprove this answer

answered Oct 28 '12 at 17:20


nebulae

2,26711215

This is the best solution using jquery. short and sweet. – John Henckel Oct 18 '16 at 14:22

1

I did a performance test and this solution seems to be roughly 2x faster than the JSON.stringify solution. – meehocz Oct 2 '17 at 13:04

add a comment

up vote

3

down vote

forget eval() (is the most misused feature of JS and makes the code slow) and slice(0) (works for simple data types only)


This is the best solution for me:


Object.prototype.clone = function() {

var myObj = (this instanceof Array) ? [] : {};

for (i in this) {

if (i != 'clone') {

if (this[i] && typeof this[i] == "object") {

myObj[i] = this[i].clone();

} else

myObj[i] = this[i];

}

}

return myObj;

};

shareimprove this answer

edited Jan 10 '12 at 11:47

answered Jan 10 '12 at 11:21


krupar

31335

add a comment

up vote

3

down vote

I was pretty frustrated by this problem. Apparently the problem arises when you send in a generic Array to the $.extend method. So, to fix it, I added a little check, and it works perfectly with generic arrays, jQuery arrays, and any objects.


jQuery.extend({

deepclone: function(objThing) {

// return jQuery.extend(true, {}, objThing);

/// Fix for arrays, without this, arrays passed in are returned as OBJECTS! WTF?!?!

if ( jQuery.isArray(objThing) ) {

return jQuery.makeArray( jQuery.deepclone($(objThing)) );

}

return jQuery.extend(true, {}, objThing);

},

});

Invoke using:


var arrNewArrayClone = jQuery.deepclone(arrOriginalArray);

// Or more simply/commonly

var arrNewArrayClone = $.deepclone(arrOriginalArray);

shareimprove this answer

answered Jun 4 '12 at 17:46


Brak

13517

deepclone? I use jquery-1.9.1 and it doesnot support this method. Is it method of more modern version? – user2783091 Oct 1 '14 at 5:30

@user2783091 he is extending JQuery to add that function. Its not something that comes out of the box – JorgeeFG Oct 13 '14 at 16:33

add a comment

up vote

3

down vote

This method is very simple and you can modify your clone without modify the original array.


// Original Array

let array = [{name: 'Rafael'}, {name: 'Matheus'}];


// Cloning Array

let clone = array.map(a => {return {...a}})


// Editing the cloned array

clone[1].name = 'Carlos';



console.log('array', array)

// [{name: 'Rafael'}, {name: 'Matheus'}]


console.log('clone', clone)

// [{name: 'Rafael'}, {name: 'Carlos'}]

Run code snippetExpand snippet

shareimprove this answer

answered May 4 '17 at 3:55


Rafael Grilli

344211

add a comment

up vote

3

down vote

I use the new ECMAScript 6 Object.assign method :


let oldObject = [1,3,5,"test"];

let newObject = Object.assign({}, oldObject);

the first argument of this method is the array to be update, we pass an empty object because we want to have a new object.


we can also use this syntax, which is the same but shorter :


let newObject = [...oldObject];

shareimprove this answer

edited Aug 23 '17 at 12:40

answered Aug 23 '17 at 11:08


Chtiwi Malek

6,03514450

add a comment

up vote

2

down vote

We can invent a simple recursive Array method to clone multidimensional arrays. While the objects within the nested arrays keep their reference to the corresponding objects in the source array, arrays won't.


Array.prototype.clone = function(){

return this.map(e => Array.isArray(e) ? e.clone() : e);

};


var arr = [ 1, 2, 3, 4, [ 1, 2, [ 1, 2, 3 ], 4 , 5], 6 ],

brr = arr.clone();

brr[4][2][1] = "two";

console.log(JSON.stringify(arr));

console.log(JSON.stringify(brr));

Run code snippetExpand snippet

shareimprove this answer

answered Jun 16 '16 at 12:55


Redu

11.3k22229

add a comment

up vote

2

down vote

This deeply copies arrays, objects, null and other scalar values, and also deeply copies any properties on non-native functions (which is pretty uncommon but possible). (For efficiency, we do not attempt to copy non-numeric properties on arrays.)


function deepClone (item) {

if (Array.isArray(item)) {

var newArr = [];

for (var i = item.length; i-- > 0;) {

newArr[i] = deepClone(item[i]);

}

return newArr;

}

if (typeof item === 'function' && !(/\(\) \{ \[native/).test(item.toString())) {

var obj;

eval('obj = '+ item.toString());

for (var k in item) {

obj[k] = deepClone(item[k]);

}

return obj;

}

if (item && typeof item === 'object') {

var obj = {};

for (var k in item) {

obj[k] = deepClone(item[k]);

}

return obj;

}

return item;

}

shareimprove this answer

edited Oct 5 '16 at 1:30

answered Oct 3 '16 at 22:38


Brett Zamir

8,88122753

add a comment

up vote

1

down vote

with jQuery:


var target= [];

$.each(source, function() {target.push( $.extend({},this));});

shareimprove this answer

answered Apr 2 '12 at 23:29


lujan99

212

It would work, but is very inefficient. – hrdwdmrbl Jun 21 '13 at 15:13

If it would work, why downvote? @jackquack – bozdoz Dec 30 '13 at 23:59

add a comment

up vote

1

down vote

The following code will perform recursively a deep copying of objects and array:


function deepCopy(obj) {

if (Object.prototype.toString.call(obj) === '[object Array]') {

var out = [], i = 0, len = obj.length;

for ( ; i < len; i++ ) {

out[i] = arguments.callee(obj[i]);

}

return out;

}

if (typeof obj === 'object') {

var out = {}, i;

for ( i in obj ) {

out[i] = arguments.callee(obj[i]);

}

return out;

}

return obj;

}

Source


shareimprove this answer

answered Mar 24 '13 at 20:46


Franck Dernoncourt

31.8k25165312

arguments.callee is not available in strict mode and has performance problems otherwise. – Brett Zamir Oct 3 '16 at 22:09

add a comment

up vote

0

down vote

I think managed to write a generic method of deep cloning any JavaScript structure mainly using Object.create which is supported in all modern browsers. The code is like this:


function deepClone (item) {

if (Array.isArray(item)) {

var newArr = [];


for (var i = item.length; i-- !== 0;) {

newArr[i] = deepClone(item[i]);

}


return newArr;

}

else if (typeof item === 'function') {

eval('var temp = '+ item.toString());

return temp;

}

else if (typeof item === 'object')

return Object.create(item);

else

return item;

}

shareimprove this answer

answered Jun 4 '15 at 14:24


ozantunca

10413

Object.create will treat item as the object's prototype, but that is different from cloning. If item is modified, changes will be reflected in its "clone" and vice versa. This approach does not work. – Brett Zamir Oct 3 '16 at 22:07

add a comment

up vote

0

down vote

For cloning the objects as well I was just going to suggest ECMAScript 6 reduce():


const newArray=myArray.reduce((array, element)=>array.push(Object.assign({}, element)), []);

But frankly I like the answer of @dinodsaurus even better. I'm just putting this version here as another option, but personally I'll be using map() as suggested by @dinodsaurus .


shareimprove this answer

answered Feb 1 '17 at 16:47


Garret Wilson

5,3501062133

add a comment

up vote

0

down vote

Depending if you have Underscore or Babel here is a Benchmark of the different way of deep cloning an array.


https://jsperf.com/object-rest-spread-vs-clone/2


Look like babel is the fastest.


var x = babel({}, obj)

shareimprove this answer

answered Feb 10 '17 at 10:18


Romuald

21558

add a comment

up vote

0

down vote

Some elegant ways for deep cloning in javascript


http://heyjavascript.com/4-creative-ways-to-clone-objects/#


1) A vanilla Javascript method for cloning objects


2) A clever exploit of the JSON library to deep-clone objects


3) Using jQuery’s $.extend() function


4) Using Mootools’ clone() function to clone objects


shareimprove this answer

edited Mar 21 '17 at 5:22

answered Mar 21 '17 at 0:54


blazehub

39110

add a comment

up vote

0

down vote

function deepCloneArray(array) {

return Array.from(Object.create(array));

}

shareimprove this answer

answered Feb 13 at 19:05


J Mora

264

4

Instead of just posting a code block, you should add an explanation of what the code does. – AfroThundr Feb 13 at 19:30

Like the Array.prototype.slice solution, the above Array.from solution provides only a shallow copy. That is, elements in the array that are objects or functions (not primitive types like number, string, boolean, or undefined) will not be independent from the source array. Maybe this poster intended to use Object.create as the mapFn argument, but even that would not completely solve the problem. – iX3 Mar 20 at 14:19

add a comment

up vote

0

down vote

var game_popularity = [

{ game: "fruit ninja", popularity: 78 },

{ game: "road runner", popularity: 20 },

{ game: "maze runner", popularity: 40 },

{ game: "ludo", popularity: 75 },

{ game: "temple runner", popularity: 86 }

];

console.log("sorted original array before clonning");

game_popularity.sort((a, b) => a.popularity < b.popularity);

console.log(game_popularity);



console.log("clone using object assign");

const cl2 = game_popularity.map(a => Object.assign({}, a));

cl2[1].game = "clash of titan";

cl2.push({ game: "logan", popularity: 57 });

console.log(cl2);



//adding new array element doesnt reflect in original array

console.log("clone using concat");

var ph = []

var cl = ph.concat(game_popularity);


//copied by reference ?

cl[0].game = "rise of civilization";


game_popularity[0].game = 'ping me';

cl.push({ game: "angry bird", popularity: 67 });

console.log(cl);


console.log("clone using ellipses");

var cl3 = [...game_popularity];

cl3.push({ game: "blue whale", popularity: 67 });

cl3[2].game = "harry potter";

console.log(cl3);


console.log("clone using json.parse");

var cl4 = JSON.parse(JSON.stringify(game_popularity));

cl4.push({ game: "home alone", popularity: 87 });

cl4[3].game ="lockhead martin";

console.log(cl4);


console.log("clone using Object.create");

var cl5 = Array.from(Object.create(game_popularity));

cl5.push({ game: "fish ville", popularity: 87 });

cl5[3].game ="veto power";

console.log(cl5);



//array function

console.log("sorted original array after clonning");

game_popularity.sort((a, b) => a.popularity < b.popularity);

console.log(game_popularity);



console.log("Object.assign deep clone object array");

console.log("json.parse deep clone object array");

console.log("concat does not deep clone object array");

console.log("ellipses does not deep clone object array");

console.log("Object.create does not deep clone object array");



Output:



sorted original array before clonning

[ { game: 'temple runner', popularity: 86 },

{ game: 'fruit ninja', popularity: 78 },

{ game: 'ludo', popularity: 75 },

{ game: 'maze runner', popularity: 40 },

{ game: 'road runner', popularity: 20 } ]

clone using object assign

[ { game: 'temple runner', popularity: 86 },

{ game: 'clash of titan', popularity: 78 },

{ game: 'ludo', popularity: 75 },

{ game: 'maze runner', popularity: 40 },

{ game: 'road runner', popularity: 20 },

{ game: 'logan', popularity: 57 } ]

clone using concat

[ { game: 'ping me', popularity: 86 },

{ game: 'fruit ninja', popularity: 78 },

{ game: 'ludo', popularity: 75 },

{ game: 'maze runner', popularity: 40 },

{ game: 'road runner', popularity: 20 },

{ game: 'angry bird', popularity: 67 } ]

clone using ellipses

[ { game: 'ping me', popularity: 86 },

{ game: 'fruit ninja', popularity: 78 },

{ game: 'harry potter', popularity: 75 },

{ game: 'maze runner', popularity: 40 },

{ game: 'road runner', popularity: 20 },

{ game: 'blue whale', popularity: 67 } ]

clone using json.parse

[ { game: 'ping me', popularity: 86 },

{ game: 'fruit ninja', popularity: 78 },

{ game: 'harry potter', popularity: 75 },

{ game: 'lockhead martin', popularity: 40 },

{ game: 'road runner', popularity: 20 },

{ game: 'home alone', popularity: 87 } ]

clone using Object.create

[ { game: 'ping me', popularity: 86 },

{ game: 'fruit ninja', popularity: 78 },

{ game: 'harry potter', popularity: 75 },

{ game: 'veto power', popularity: 40 },

{ game: 'road runner', popularity: 20 },

{ game: 'fish ville', popularity: 87 } ]

sorted original array after clonning

[ { game: 'ping me', popularity: 86 },

{ game: 'fruit ninja', popularity: 78 },

{ game: 'harry potter', popularity: 75 },

{ game: 'veto power', popularity: 40 },

{ game: 'road runner', popularity: 20 } ]


Object.assign deep clone object array

json.parse deep clone object array

concat does not deep clone object array

ellipses does not deep clone object array

Object.create does not deep clone object array

shareimprove this answer

answered Mar 18 at 7:45


sangram

14414

add a comment

up vote

0

down vote

Map will create new array from the old one (without reference to old one) and inside the map you create new object and iterate over properties (keys) and assign values from old Array object to coresponding properties to the new object.


This will create exactly the same array of objects.


let newArray = oldArray.map(a => {

let newObject = {};

Object.keys(a).forEach(propertyKey => {

newObject[propertyKey] = a[propertyKey];

});

return newObject ;

});

Так же в этом разделе:
 
MyTetra Share v.0.53
Яндекс индекс цитирования