copy array of objectsHow do I correctly clone a JavaScript object?Detecting an undefined object propertyWhat is the most efficient way to deep clone an object in JavaScript?How do I remove a property from a JavaScript object?How do I check if an array includes an object in JavaScript?How to append something to an array?How to insert an item into an array at a specific index (JavaScript)?Checking if a key exists in a JavaScript object?How to check if an object is an array?How do I remove a particular element from an array in JavaScript?For-each over an array in JavaScript?
Greatest common substring
Is expanding the research of a group into machine learning as a PhD student risky?
How do I define a right arrow with bar in LaTeX?
Student evaluations of teaching assistants
Can I use my Chinese passport to enter China after I acquired another citizenship?
How will losing mobility of one hand affect my career as a programmer?
How does residential electricity work?
Why is `const int& k = i; ++i; ` possible?
Is it correct to write "is not focus on"?
How was Earth single-handedly capable of creating 3 of the 4 gods of chaos?
Go Pregnant or Go Home
Efficiently merge handle parallel feature branches in SFDX
Implement the Thanos sorting algorithm
Can I Retrieve Email Addresses from BCC?
What is the oldest known work of fiction?
Is there any easy technique written in Bhagavad GITA to control lust?
Your magic is very sketchy
Bash method for viewing beginning and end of file
Valid Badminton Score?
Is HostGator storing my password in plaintext?
(Bedrock Edition) Loading more than six chunks at once
voltage of sounds of mp3files
Why is delta-v is the most useful quantity for planning space travel?
Should my PhD thesis be submitted under my legal name?
copy array of objects
How do I correctly clone a JavaScript object?Detecting an undefined object propertyWhat is the most efficient way to deep clone an object in JavaScript?How do I remove a property from a JavaScript object?How do I check if an array includes an object in JavaScript?How to append something to an array?How to insert an item into an array at a specific index (JavaScript)?Checking if a key exists in a JavaScript object?How to check if an object is an array?How do I remove a particular element from an array in JavaScript?For-each over an array in JavaScript?
I'm having issues creating a copy of an object array. I can't get the new reference to point to a new independent array.
function OBJ1(name, tags)
this.myname = name;
this.mytags = tags;
this.myvalue = 0;
function OBJ2(arg1)
this.arg1 = arg1;
this.myarray = [];
var OBJ1_array = [];
var result_array2 = null;
var result;
OBJ1_array = createarray1();
for (i = 0; i < 2; i++)
result = createarray2();
function createarray1()
var myarray = [];
myarray.push(new OBJ1("NAME", [1, 2, 3]));
myarray.push(new OBJ1("others", [1, 2, 3]));
myarray.push(new OBJ1("total", [1, 2, 3]));
return myarray;
function createarray2()
var newarray = $.extend(true, [], OBJ1_array); // newarray should refer to a new array, not the same one as OBJ1_array
OBJ1_array[0].myname = "CHANGED";
console.log("categories", JSON.parse(JSON.stringify(OBJ1_array)));
console.log("newarray", JSON.parse(JSON.stringify(newarray)));
Output:
testscript.js:45 categories (3) […, …, …]0: myname: "CHANGED", mytags: Array(3), myvalue: 01: myname: "others", mytags: Array(3), myvalue: 02: myname: "total", mytags: Array(3), myvalue: 0length: 3__proto__: Array(0)
testscript.js:46 newArray (3) […, …, …]0: myname: "CHANGED", mytags: Array(3), myvalue: 01: myname: "others", mytags: Array(3), myvalue: 02: myname: "total", mytags: Array(3), myvalue: 0length: 3__proto__: Array(0)
I expected OBJ1_array[0].myname="CHANGED";
to have no effect on the newly created array newArray
.
Things I've tried and didn't work:
var newArray = OBJ1_array.map(a => (...a));
var newarray=$.extend(true,[],OBJ1_array);
How can I solve this issue?
javascript jquery arrays object
add a comment |
I'm having issues creating a copy of an object array. I can't get the new reference to point to a new independent array.
function OBJ1(name, tags)
this.myname = name;
this.mytags = tags;
this.myvalue = 0;
function OBJ2(arg1)
this.arg1 = arg1;
this.myarray = [];
var OBJ1_array = [];
var result_array2 = null;
var result;
OBJ1_array = createarray1();
for (i = 0; i < 2; i++)
result = createarray2();
function createarray1()
var myarray = [];
myarray.push(new OBJ1("NAME", [1, 2, 3]));
myarray.push(new OBJ1("others", [1, 2, 3]));
myarray.push(new OBJ1("total", [1, 2, 3]));
return myarray;
function createarray2()
var newarray = $.extend(true, [], OBJ1_array); // newarray should refer to a new array, not the same one as OBJ1_array
OBJ1_array[0].myname = "CHANGED";
console.log("categories", JSON.parse(JSON.stringify(OBJ1_array)));
console.log("newarray", JSON.parse(JSON.stringify(newarray)));
Output:
testscript.js:45 categories (3) […, …, …]0: myname: "CHANGED", mytags: Array(3), myvalue: 01: myname: "others", mytags: Array(3), myvalue: 02: myname: "total", mytags: Array(3), myvalue: 0length: 3__proto__: Array(0)
testscript.js:46 newArray (3) […, …, …]0: myname: "CHANGED", mytags: Array(3), myvalue: 01: myname: "others", mytags: Array(3), myvalue: 02: myname: "total", mytags: Array(3), myvalue: 0length: 3__proto__: Array(0)
I expected OBJ1_array[0].myname="CHANGED";
to have no effect on the newly created array newArray
.
Things I've tried and didn't work:
var newArray = OBJ1_array.map(a => (...a));
var newarray=$.extend(true,[],OBJ1_array);
How can I solve this issue?
javascript jquery arrays object
A good article with possible ways: medium.com/@Farzad_YZ/…
– harish sharma
Mar 8 at 10:00
Possible duplicate of How do I correctly clone a JavaScript object?
– cнŝdk
Mar 8 at 10:05
add a comment |
I'm having issues creating a copy of an object array. I can't get the new reference to point to a new independent array.
function OBJ1(name, tags)
this.myname = name;
this.mytags = tags;
this.myvalue = 0;
function OBJ2(arg1)
this.arg1 = arg1;
this.myarray = [];
var OBJ1_array = [];
var result_array2 = null;
var result;
OBJ1_array = createarray1();
for (i = 0; i < 2; i++)
result = createarray2();
function createarray1()
var myarray = [];
myarray.push(new OBJ1("NAME", [1, 2, 3]));
myarray.push(new OBJ1("others", [1, 2, 3]));
myarray.push(new OBJ1("total", [1, 2, 3]));
return myarray;
function createarray2()
var newarray = $.extend(true, [], OBJ1_array); // newarray should refer to a new array, not the same one as OBJ1_array
OBJ1_array[0].myname = "CHANGED";
console.log("categories", JSON.parse(JSON.stringify(OBJ1_array)));
console.log("newarray", JSON.parse(JSON.stringify(newarray)));
Output:
testscript.js:45 categories (3) […, …, …]0: myname: "CHANGED", mytags: Array(3), myvalue: 01: myname: "others", mytags: Array(3), myvalue: 02: myname: "total", mytags: Array(3), myvalue: 0length: 3__proto__: Array(0)
testscript.js:46 newArray (3) […, …, …]0: myname: "CHANGED", mytags: Array(3), myvalue: 01: myname: "others", mytags: Array(3), myvalue: 02: myname: "total", mytags: Array(3), myvalue: 0length: 3__proto__: Array(0)
I expected OBJ1_array[0].myname="CHANGED";
to have no effect on the newly created array newArray
.
Things I've tried and didn't work:
var newArray = OBJ1_array.map(a => (...a));
var newarray=$.extend(true,[],OBJ1_array);
How can I solve this issue?
javascript jquery arrays object
I'm having issues creating a copy of an object array. I can't get the new reference to point to a new independent array.
function OBJ1(name, tags)
this.myname = name;
this.mytags = tags;
this.myvalue = 0;
function OBJ2(arg1)
this.arg1 = arg1;
this.myarray = [];
var OBJ1_array = [];
var result_array2 = null;
var result;
OBJ1_array = createarray1();
for (i = 0; i < 2; i++)
result = createarray2();
function createarray1()
var myarray = [];
myarray.push(new OBJ1("NAME", [1, 2, 3]));
myarray.push(new OBJ1("others", [1, 2, 3]));
myarray.push(new OBJ1("total", [1, 2, 3]));
return myarray;
function createarray2()
var newarray = $.extend(true, [], OBJ1_array); // newarray should refer to a new array, not the same one as OBJ1_array
OBJ1_array[0].myname = "CHANGED";
console.log("categories", JSON.parse(JSON.stringify(OBJ1_array)));
console.log("newarray", JSON.parse(JSON.stringify(newarray)));
Output:
testscript.js:45 categories (3) […, …, …]0: myname: "CHANGED", mytags: Array(3), myvalue: 01: myname: "others", mytags: Array(3), myvalue: 02: myname: "total", mytags: Array(3), myvalue: 0length: 3__proto__: Array(0)
testscript.js:46 newArray (3) […, …, …]0: myname: "CHANGED", mytags: Array(3), myvalue: 01: myname: "others", mytags: Array(3), myvalue: 02: myname: "total", mytags: Array(3), myvalue: 0length: 3__proto__: Array(0)
I expected OBJ1_array[0].myname="CHANGED";
to have no effect on the newly created array newArray
.
Things I've tried and didn't work:
var newArray = OBJ1_array.map(a => (...a));
var newarray=$.extend(true,[],OBJ1_array);
How can I solve this issue?
javascript jquery arrays object
javascript jquery arrays object
edited Mar 8 at 9:58
jo_va
7,5332829
7,5332829
asked Mar 8 at 9:53
H_squaredH_squared
77321125
77321125
A good article with possible ways: medium.com/@Farzad_YZ/…
– harish sharma
Mar 8 at 10:00
Possible duplicate of How do I correctly clone a JavaScript object?
– cнŝdk
Mar 8 at 10:05
add a comment |
A good article with possible ways: medium.com/@Farzad_YZ/…
– harish sharma
Mar 8 at 10:00
Possible duplicate of How do I correctly clone a JavaScript object?
– cнŝdk
Mar 8 at 10:05
A good article with possible ways: medium.com/@Farzad_YZ/…
– harish sharma
Mar 8 at 10:00
A good article with possible ways: medium.com/@Farzad_YZ/…
– harish sharma
Mar 8 at 10:00
Possible duplicate of How do I correctly clone a JavaScript object?
– cнŝdk
Mar 8 at 10:05
Possible duplicate of How do I correctly clone a JavaScript object?
– cнŝdk
Mar 8 at 10:05
add a comment |
6 Answers
6
active
oldest
votes
The $.extend
documentation says the following:
Undefined properties are not copied. However, properties inherited from the object's prototype will be copied over. Properties that are an object constructed via
new MyCustomObject(args)
, or built-in JavaScript types such as Date or RegExp, are not re-constructed and will appear as plain Objects in the resulting object or array.
This means that the array with all plain object in it will be deeply merged/copied. However objects created with the new
keyword will not be reconstructed. This leaves us with the following scenario:
The array copy works just fine, however since the elements in the array are created using the new
keyword they are not further merged. When altering the array itself (pushing, popping, etc.) you can see that the array is indeed a copy.
The issue here is that you access one of the elements in the array and change the object (created with the new
keyword). Both arrays still point to the same object, thus when reading from the other array which hold the same object reference you will also see this change.
To resolve this issue you have to also make a copy of each object in the array. Depending on your use-case you might be able to use Object.assign
or Object.create
have a look at the documentation before using them blindly.
I've also created a minimal example of the problem you face to give you some better understanding of the issue.
// setup
var array1, array2, array3, array4;
function Dummy(name) this.name = name
// test #1 - using plain objects
array1 = [ name: 'Foo' ];
array2 = $.extend(true, [], array1);
array1[0].name = 'Bar';
console.log(array1[0].name, array2[0].name);
// test #2 - using the `new` keyword
array3 = [new Dummy('Foo')];
array4 = $.extend(true, [], array3);
array3[0].name = 'Bar';
console.log(array3[0].name, array4[0].name);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
Additional reading material: webreflection.co.uk/blog/2015/10/06/…
– 3limin4t0r
Mar 8 at 19:23
add a comment |
The problem is in your loop and OBJ1 function. first time the OBJ1_array is ok but when you come second time its valued already changed..
you can try this code
function OBJ1(name, tags)
return myname:name, tags:tags
//this.myvalue = 0;
function OBJ2(arg1)
this.arg1 = arg1;
this.myarray = [];
var OBJ1_array = [];
var result_array2 = null;
var result;
OBJ1_array = createarray1();
for (i = 0; i < 2; i++)
let tempArr = $.extend(true, [], OBJ1_array);
result = createarray2();
OBJ1_array = tempArr;
function createarray1()
let myarray = [];
myarray.push(new OBJ1("NAME", [1, 2, 3]));
myarray.push(new OBJ1("others", [1, 2, 3]));
myarray.push(new OBJ1("total", [1, 2, 3]));
return myarray;
function createarray2()
let newarray =$.extend(true, [], OBJ1_array);// newarray should refer to a new array, not the same one as OBJ1_array
OBJ1_array[0].myname = "CHANGED";
console.log("categories", JSON.parse(JSON.stringify(OBJ1_array)));
console.log("newarray", JSON.parse(JSON.stringify(newarray)));
add a comment |
Updated the answer. Easiest way to achieve what you want is to use JSON.stringify
with JSON.parse
to create a unlinked copy of array of objects.
const OBJ1 = (name, tags) => (
myname: name,
mytags: tags,
myvalue: 0,
)
function createarray1()
var myarray=[];
myarray.push(OBJ1("NAME", [1,2,3]));
myarray.push(OBJ1("others", [1,2,3]));
myarray.push(OBJ1("total", [1,2,3]));
return myarray;
const arr = createarray1()
// here you create a copy of array
const newArr = JSON.parse(JSON.stringify(arr))
// apply changes directly to the copy
newArr[0].myname = 'Something else'
console.log(newArr)
console.log(arr)
now both newArr and arr contain 'Something else' . Addconsole.log(arr)
to the end and see for yourself.
– H_squared
Mar 8 at 10:06
@H_squared updated the answer.
– dporechny
Mar 8 at 10:28
Does not copy methods. in my actual code, my Object contains methods.
– H_squared
Mar 8 at 11:33
add a comment |
Arrays and Objects are reference types, which means that when you make a copy by assignment, you are simply copying the reference and not the underlying array/object. In your case, when copying the array, you copy all of the object references, which will still point to the objects in your original array. You need to clone the objects too for it to work.
Use Array.map()
to iterate over your array and copy each item.
Use Object.create()
to make a shallow clone of each object. This function takes a prototype and property descriptors to create a new object. You can use Object.getPrototypeOf()
Object.getOwnPropertyDescriptors()
to pass it the prototype and property descriptors of your input object.
function OBJ1(name)
this.myname = name;
const array1 = [new OBJ1("NAME")];
const array2 = array1.map(obj =>
Object.create(
Object.getPrototypeOf(obj),
Object.getOwnPropertyDescriptors(obj)
)
);
array2[0].myname = 'Jack';
console.log(array1[0].myname);
console.log(array2[0].myname);
const array2 = array1.map(Object.create); Here you are creating two properties by name "myname" in object and its prototype.
– RK_15
Mar 8 at 10:12
this creates array2, but does not make a copy. Addthis.tags=tags
in your constructor, and you will see that the array in array2 is empty.
– H_squared
Mar 8 at 10:14
@RK_15, could you elaborate please, I do not understand why this is not copying the array and the inner object, I am mapping on array1 and piping each item through Object.create, which creates a new object with the same prototype/properties as the original object
– jo_va
Mar 8 at 10:17
@H_squared, I do not understand, could you elaborate please ?
– jo_va
Mar 8 at 10:18
@jo_va first the resultant object is not an array it is a plain object with numeric indexes second "Object.create" methods first argument is the new prototype for resultant object i.e. all the object properties will shift to its prototype. Just log the array2 before changing "myname" property and you will not see that property in the object because it is in prototype of that object.
– RK_15
Mar 8 at 10:20
|
show 6 more comments
I think you need a deep cloning of your object. please use below function
function clone(src)
var ret=(src instanceof Array ? [] : );
for(var key in src)
if(!src.hasOwnProperty(key)) continue;
var val=src[key];
if(val && typeof(val)=='object') val=clone(val);
ret[key]=val;
return ret;
function OBJ1(name, tags)
this.myname = name;
this.mytags = tags;
this.myvalue = 0;
function OBJ2(arg1)
this.arg1 = arg1;
this.myarray = [];
var OBJ1_array = [];
var result_array2 = null;
var result;
OBJ1_array = createarray1();
for (i = 0; i < 2; i++)
result = createarray2();
function createarray1()
var myarray = [];
myarray.push(new OBJ1("NAME", [1, 2, 3]));
myarray.push(new OBJ1("others", [1, 2, 3]));
myarray.push(new OBJ1("total", [1, 2, 3]));
return myarray;
function createarray2()
var newarray = clone(OBJ1_array) ; // newarray should refer to a new array, not the same one as OBJ1_array
OBJ1_array[0].myname = "CHANGED";
console.log("categories", JSON.parse(JSON.stringify(OBJ1_array)));
console.log("newarray", JSON.parse(JSON.stringify(newarray)));
Much Simpler Approach
var cloneOfOBJ1_array = JSON.parse(JSON.stringify(OBJ1_array));
Does not copy methods. in my actual code, my Object contains methods.
– H_squared
Mar 8 at 11:33
@H_squared put your exact requirement in question
– Negi Rox
Mar 8 at 12:58
add a comment |
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));
Answer copy pasted from somewhere else. Plus I've tried this and it didn't workas mentioned in the original post.
– H_squared
Mar 8 at 10:17
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55060656%2fcopy-array-of-objects%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
6 Answers
6
active
oldest
votes
6 Answers
6
active
oldest
votes
active
oldest
votes
active
oldest
votes
The $.extend
documentation says the following:
Undefined properties are not copied. However, properties inherited from the object's prototype will be copied over. Properties that are an object constructed via
new MyCustomObject(args)
, or built-in JavaScript types such as Date or RegExp, are not re-constructed and will appear as plain Objects in the resulting object or array.
This means that the array with all plain object in it will be deeply merged/copied. However objects created with the new
keyword will not be reconstructed. This leaves us with the following scenario:
The array copy works just fine, however since the elements in the array are created using the new
keyword they are not further merged. When altering the array itself (pushing, popping, etc.) you can see that the array is indeed a copy.
The issue here is that you access one of the elements in the array and change the object (created with the new
keyword). Both arrays still point to the same object, thus when reading from the other array which hold the same object reference you will also see this change.
To resolve this issue you have to also make a copy of each object in the array. Depending on your use-case you might be able to use Object.assign
or Object.create
have a look at the documentation before using them blindly.
I've also created a minimal example of the problem you face to give you some better understanding of the issue.
// setup
var array1, array2, array3, array4;
function Dummy(name) this.name = name
// test #1 - using plain objects
array1 = [ name: 'Foo' ];
array2 = $.extend(true, [], array1);
array1[0].name = 'Bar';
console.log(array1[0].name, array2[0].name);
// test #2 - using the `new` keyword
array3 = [new Dummy('Foo')];
array4 = $.extend(true, [], array3);
array3[0].name = 'Bar';
console.log(array3[0].name, array4[0].name);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
Additional reading material: webreflection.co.uk/blog/2015/10/06/…
– 3limin4t0r
Mar 8 at 19:23
add a comment |
The $.extend
documentation says the following:
Undefined properties are not copied. However, properties inherited from the object's prototype will be copied over. Properties that are an object constructed via
new MyCustomObject(args)
, or built-in JavaScript types such as Date or RegExp, are not re-constructed and will appear as plain Objects in the resulting object or array.
This means that the array with all plain object in it will be deeply merged/copied. However objects created with the new
keyword will not be reconstructed. This leaves us with the following scenario:
The array copy works just fine, however since the elements in the array are created using the new
keyword they are not further merged. When altering the array itself (pushing, popping, etc.) you can see that the array is indeed a copy.
The issue here is that you access one of the elements in the array and change the object (created with the new
keyword). Both arrays still point to the same object, thus when reading from the other array which hold the same object reference you will also see this change.
To resolve this issue you have to also make a copy of each object in the array. Depending on your use-case you might be able to use Object.assign
or Object.create
have a look at the documentation before using them blindly.
I've also created a minimal example of the problem you face to give you some better understanding of the issue.
// setup
var array1, array2, array3, array4;
function Dummy(name) this.name = name
// test #1 - using plain objects
array1 = [ name: 'Foo' ];
array2 = $.extend(true, [], array1);
array1[0].name = 'Bar';
console.log(array1[0].name, array2[0].name);
// test #2 - using the `new` keyword
array3 = [new Dummy('Foo')];
array4 = $.extend(true, [], array3);
array3[0].name = 'Bar';
console.log(array3[0].name, array4[0].name);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
Additional reading material: webreflection.co.uk/blog/2015/10/06/…
– 3limin4t0r
Mar 8 at 19:23
add a comment |
The $.extend
documentation says the following:
Undefined properties are not copied. However, properties inherited from the object's prototype will be copied over. Properties that are an object constructed via
new MyCustomObject(args)
, or built-in JavaScript types such as Date or RegExp, are not re-constructed and will appear as plain Objects in the resulting object or array.
This means that the array with all plain object in it will be deeply merged/copied. However objects created with the new
keyword will not be reconstructed. This leaves us with the following scenario:
The array copy works just fine, however since the elements in the array are created using the new
keyword they are not further merged. When altering the array itself (pushing, popping, etc.) you can see that the array is indeed a copy.
The issue here is that you access one of the elements in the array and change the object (created with the new
keyword). Both arrays still point to the same object, thus when reading from the other array which hold the same object reference you will also see this change.
To resolve this issue you have to also make a copy of each object in the array. Depending on your use-case you might be able to use Object.assign
or Object.create
have a look at the documentation before using them blindly.
I've also created a minimal example of the problem you face to give you some better understanding of the issue.
// setup
var array1, array2, array3, array4;
function Dummy(name) this.name = name
// test #1 - using plain objects
array1 = [ name: 'Foo' ];
array2 = $.extend(true, [], array1);
array1[0].name = 'Bar';
console.log(array1[0].name, array2[0].name);
// test #2 - using the `new` keyword
array3 = [new Dummy('Foo')];
array4 = $.extend(true, [], array3);
array3[0].name = 'Bar';
console.log(array3[0].name, array4[0].name);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
The $.extend
documentation says the following:
Undefined properties are not copied. However, properties inherited from the object's prototype will be copied over. Properties that are an object constructed via
new MyCustomObject(args)
, or built-in JavaScript types such as Date or RegExp, are not re-constructed and will appear as plain Objects in the resulting object or array.
This means that the array with all plain object in it will be deeply merged/copied. However objects created with the new
keyword will not be reconstructed. This leaves us with the following scenario:
The array copy works just fine, however since the elements in the array are created using the new
keyword they are not further merged. When altering the array itself (pushing, popping, etc.) you can see that the array is indeed a copy.
The issue here is that you access one of the elements in the array and change the object (created with the new
keyword). Both arrays still point to the same object, thus when reading from the other array which hold the same object reference you will also see this change.
To resolve this issue you have to also make a copy of each object in the array. Depending on your use-case you might be able to use Object.assign
or Object.create
have a look at the documentation before using them blindly.
I've also created a minimal example of the problem you face to give you some better understanding of the issue.
// setup
var array1, array2, array3, array4;
function Dummy(name) this.name = name
// test #1 - using plain objects
array1 = [ name: 'Foo' ];
array2 = $.extend(true, [], array1);
array1[0].name = 'Bar';
console.log(array1[0].name, array2[0].name);
// test #2 - using the `new` keyword
array3 = [new Dummy('Foo')];
array4 = $.extend(true, [], array3);
array3[0].name = 'Bar';
console.log(array3[0].name, array4[0].name);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
// setup
var array1, array2, array3, array4;
function Dummy(name) this.name = name
// test #1 - using plain objects
array1 = [ name: 'Foo' ];
array2 = $.extend(true, [], array1);
array1[0].name = 'Bar';
console.log(array1[0].name, array2[0].name);
// test #2 - using the `new` keyword
array3 = [new Dummy('Foo')];
array4 = $.extend(true, [], array3);
array3[0].name = 'Bar';
console.log(array3[0].name, array4[0].name);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
// setup
var array1, array2, array3, array4;
function Dummy(name) this.name = name
// test #1 - using plain objects
array1 = [ name: 'Foo' ];
array2 = $.extend(true, [], array1);
array1[0].name = 'Bar';
console.log(array1[0].name, array2[0].name);
// test #2 - using the `new` keyword
array3 = [new Dummy('Foo')];
array4 = $.extend(true, [], array3);
array3[0].name = 'Bar';
console.log(array3[0].name, array4[0].name);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
edited Mar 8 at 21:30
answered Mar 8 at 11:42
3limin4t0r3limin4t0r
3,102823
3,102823
Additional reading material: webreflection.co.uk/blog/2015/10/06/…
– 3limin4t0r
Mar 8 at 19:23
add a comment |
Additional reading material: webreflection.co.uk/blog/2015/10/06/…
– 3limin4t0r
Mar 8 at 19:23
Additional reading material: webreflection.co.uk/blog/2015/10/06/…
– 3limin4t0r
Mar 8 at 19:23
Additional reading material: webreflection.co.uk/blog/2015/10/06/…
– 3limin4t0r
Mar 8 at 19:23
add a comment |
The problem is in your loop and OBJ1 function. first time the OBJ1_array is ok but when you come second time its valued already changed..
you can try this code
function OBJ1(name, tags)
return myname:name, tags:tags
//this.myvalue = 0;
function OBJ2(arg1)
this.arg1 = arg1;
this.myarray = [];
var OBJ1_array = [];
var result_array2 = null;
var result;
OBJ1_array = createarray1();
for (i = 0; i < 2; i++)
let tempArr = $.extend(true, [], OBJ1_array);
result = createarray2();
OBJ1_array = tempArr;
function createarray1()
let myarray = [];
myarray.push(new OBJ1("NAME", [1, 2, 3]));
myarray.push(new OBJ1("others", [1, 2, 3]));
myarray.push(new OBJ1("total", [1, 2, 3]));
return myarray;
function createarray2()
let newarray =$.extend(true, [], OBJ1_array);// newarray should refer to a new array, not the same one as OBJ1_array
OBJ1_array[0].myname = "CHANGED";
console.log("categories", JSON.parse(JSON.stringify(OBJ1_array)));
console.log("newarray", JSON.parse(JSON.stringify(newarray)));
add a comment |
The problem is in your loop and OBJ1 function. first time the OBJ1_array is ok but when you come second time its valued already changed..
you can try this code
function OBJ1(name, tags)
return myname:name, tags:tags
//this.myvalue = 0;
function OBJ2(arg1)
this.arg1 = arg1;
this.myarray = [];
var OBJ1_array = [];
var result_array2 = null;
var result;
OBJ1_array = createarray1();
for (i = 0; i < 2; i++)
let tempArr = $.extend(true, [], OBJ1_array);
result = createarray2();
OBJ1_array = tempArr;
function createarray1()
let myarray = [];
myarray.push(new OBJ1("NAME", [1, 2, 3]));
myarray.push(new OBJ1("others", [1, 2, 3]));
myarray.push(new OBJ1("total", [1, 2, 3]));
return myarray;
function createarray2()
let newarray =$.extend(true, [], OBJ1_array);// newarray should refer to a new array, not the same one as OBJ1_array
OBJ1_array[0].myname = "CHANGED";
console.log("categories", JSON.parse(JSON.stringify(OBJ1_array)));
console.log("newarray", JSON.parse(JSON.stringify(newarray)));
add a comment |
The problem is in your loop and OBJ1 function. first time the OBJ1_array is ok but when you come second time its valued already changed..
you can try this code
function OBJ1(name, tags)
return myname:name, tags:tags
//this.myvalue = 0;
function OBJ2(arg1)
this.arg1 = arg1;
this.myarray = [];
var OBJ1_array = [];
var result_array2 = null;
var result;
OBJ1_array = createarray1();
for (i = 0; i < 2; i++)
let tempArr = $.extend(true, [], OBJ1_array);
result = createarray2();
OBJ1_array = tempArr;
function createarray1()
let myarray = [];
myarray.push(new OBJ1("NAME", [1, 2, 3]));
myarray.push(new OBJ1("others", [1, 2, 3]));
myarray.push(new OBJ1("total", [1, 2, 3]));
return myarray;
function createarray2()
let newarray =$.extend(true, [], OBJ1_array);// newarray should refer to a new array, not the same one as OBJ1_array
OBJ1_array[0].myname = "CHANGED";
console.log("categories", JSON.parse(JSON.stringify(OBJ1_array)));
console.log("newarray", JSON.parse(JSON.stringify(newarray)));
The problem is in your loop and OBJ1 function. first time the OBJ1_array is ok but when you come second time its valued already changed..
you can try this code
function OBJ1(name, tags)
return myname:name, tags:tags
//this.myvalue = 0;
function OBJ2(arg1)
this.arg1 = arg1;
this.myarray = [];
var OBJ1_array = [];
var result_array2 = null;
var result;
OBJ1_array = createarray1();
for (i = 0; i < 2; i++)
let tempArr = $.extend(true, [], OBJ1_array);
result = createarray2();
OBJ1_array = tempArr;
function createarray1()
let myarray = [];
myarray.push(new OBJ1("NAME", [1, 2, 3]));
myarray.push(new OBJ1("others", [1, 2, 3]));
myarray.push(new OBJ1("total", [1, 2, 3]));
return myarray;
function createarray2()
let newarray =$.extend(true, [], OBJ1_array);// newarray should refer to a new array, not the same one as OBJ1_array
OBJ1_array[0].myname = "CHANGED";
console.log("categories", JSON.parse(JSON.stringify(OBJ1_array)));
console.log("newarray", JSON.parse(JSON.stringify(newarray)));
edited Mar 8 at 10:30
answered Mar 8 at 10:19
Zulqarnain JalilZulqarnain Jalil
433520
433520
add a comment |
add a comment |
Updated the answer. Easiest way to achieve what you want is to use JSON.stringify
with JSON.parse
to create a unlinked copy of array of objects.
const OBJ1 = (name, tags) => (
myname: name,
mytags: tags,
myvalue: 0,
)
function createarray1()
var myarray=[];
myarray.push(OBJ1("NAME", [1,2,3]));
myarray.push(OBJ1("others", [1,2,3]));
myarray.push(OBJ1("total", [1,2,3]));
return myarray;
const arr = createarray1()
// here you create a copy of array
const newArr = JSON.parse(JSON.stringify(arr))
// apply changes directly to the copy
newArr[0].myname = 'Something else'
console.log(newArr)
console.log(arr)
now both newArr and arr contain 'Something else' . Addconsole.log(arr)
to the end and see for yourself.
– H_squared
Mar 8 at 10:06
@H_squared updated the answer.
– dporechny
Mar 8 at 10:28
Does not copy methods. in my actual code, my Object contains methods.
– H_squared
Mar 8 at 11:33
add a comment |
Updated the answer. Easiest way to achieve what you want is to use JSON.stringify
with JSON.parse
to create a unlinked copy of array of objects.
const OBJ1 = (name, tags) => (
myname: name,
mytags: tags,
myvalue: 0,
)
function createarray1()
var myarray=[];
myarray.push(OBJ1("NAME", [1,2,3]));
myarray.push(OBJ1("others", [1,2,3]));
myarray.push(OBJ1("total", [1,2,3]));
return myarray;
const arr = createarray1()
// here you create a copy of array
const newArr = JSON.parse(JSON.stringify(arr))
// apply changes directly to the copy
newArr[0].myname = 'Something else'
console.log(newArr)
console.log(arr)
now both newArr and arr contain 'Something else' . Addconsole.log(arr)
to the end and see for yourself.
– H_squared
Mar 8 at 10:06
@H_squared updated the answer.
– dporechny
Mar 8 at 10:28
Does not copy methods. in my actual code, my Object contains methods.
– H_squared
Mar 8 at 11:33
add a comment |
Updated the answer. Easiest way to achieve what you want is to use JSON.stringify
with JSON.parse
to create a unlinked copy of array of objects.
const OBJ1 = (name, tags) => (
myname: name,
mytags: tags,
myvalue: 0,
)
function createarray1()
var myarray=[];
myarray.push(OBJ1("NAME", [1,2,3]));
myarray.push(OBJ1("others", [1,2,3]));
myarray.push(OBJ1("total", [1,2,3]));
return myarray;
const arr = createarray1()
// here you create a copy of array
const newArr = JSON.parse(JSON.stringify(arr))
// apply changes directly to the copy
newArr[0].myname = 'Something else'
console.log(newArr)
console.log(arr)
Updated the answer. Easiest way to achieve what you want is to use JSON.stringify
with JSON.parse
to create a unlinked copy of array of objects.
const OBJ1 = (name, tags) => (
myname: name,
mytags: tags,
myvalue: 0,
)
function createarray1()
var myarray=[];
myarray.push(OBJ1("NAME", [1,2,3]));
myarray.push(OBJ1("others", [1,2,3]));
myarray.push(OBJ1("total", [1,2,3]));
return myarray;
const arr = createarray1()
// here you create a copy of array
const newArr = JSON.parse(JSON.stringify(arr))
// apply changes directly to the copy
newArr[0].myname = 'Something else'
console.log(newArr)
console.log(arr)
const OBJ1 = (name, tags) => (
myname: name,
mytags: tags,
myvalue: 0,
)
function createarray1()
var myarray=[];
myarray.push(OBJ1("NAME", [1,2,3]));
myarray.push(OBJ1("others", [1,2,3]));
myarray.push(OBJ1("total", [1,2,3]));
return myarray;
const arr = createarray1()
// here you create a copy of array
const newArr = JSON.parse(JSON.stringify(arr))
// apply changes directly to the copy
newArr[0].myname = 'Something else'
console.log(newArr)
console.log(arr)
const OBJ1 = (name, tags) => (
myname: name,
mytags: tags,
myvalue: 0,
)
function createarray1()
var myarray=[];
myarray.push(OBJ1("NAME", [1,2,3]));
myarray.push(OBJ1("others", [1,2,3]));
myarray.push(OBJ1("total", [1,2,3]));
return myarray;
const arr = createarray1()
// here you create a copy of array
const newArr = JSON.parse(JSON.stringify(arr))
// apply changes directly to the copy
newArr[0].myname = 'Something else'
console.log(newArr)
console.log(arr)
edited Mar 8 at 10:28
answered Mar 8 at 9:59
dporechnydporechny
50229
50229
now both newArr and arr contain 'Something else' . Addconsole.log(arr)
to the end and see for yourself.
– H_squared
Mar 8 at 10:06
@H_squared updated the answer.
– dporechny
Mar 8 at 10:28
Does not copy methods. in my actual code, my Object contains methods.
– H_squared
Mar 8 at 11:33
add a comment |
now both newArr and arr contain 'Something else' . Addconsole.log(arr)
to the end and see for yourself.
– H_squared
Mar 8 at 10:06
@H_squared updated the answer.
– dporechny
Mar 8 at 10:28
Does not copy methods. in my actual code, my Object contains methods.
– H_squared
Mar 8 at 11:33
now both newArr and arr contain 'Something else' . Add
console.log(arr)
to the end and see for yourself.– H_squared
Mar 8 at 10:06
now both newArr and arr contain 'Something else' . Add
console.log(arr)
to the end and see for yourself.– H_squared
Mar 8 at 10:06
@H_squared updated the answer.
– dporechny
Mar 8 at 10:28
@H_squared updated the answer.
– dporechny
Mar 8 at 10:28
Does not copy methods. in my actual code, my Object contains methods.
– H_squared
Mar 8 at 11:33
Does not copy methods. in my actual code, my Object contains methods.
– H_squared
Mar 8 at 11:33
add a comment |
Arrays and Objects are reference types, which means that when you make a copy by assignment, you are simply copying the reference and not the underlying array/object. In your case, when copying the array, you copy all of the object references, which will still point to the objects in your original array. You need to clone the objects too for it to work.
Use Array.map()
to iterate over your array and copy each item.
Use Object.create()
to make a shallow clone of each object. This function takes a prototype and property descriptors to create a new object. You can use Object.getPrototypeOf()
Object.getOwnPropertyDescriptors()
to pass it the prototype and property descriptors of your input object.
function OBJ1(name)
this.myname = name;
const array1 = [new OBJ1("NAME")];
const array2 = array1.map(obj =>
Object.create(
Object.getPrototypeOf(obj),
Object.getOwnPropertyDescriptors(obj)
)
);
array2[0].myname = 'Jack';
console.log(array1[0].myname);
console.log(array2[0].myname);
const array2 = array1.map(Object.create); Here you are creating two properties by name "myname" in object and its prototype.
– RK_15
Mar 8 at 10:12
this creates array2, but does not make a copy. Addthis.tags=tags
in your constructor, and you will see that the array in array2 is empty.
– H_squared
Mar 8 at 10:14
@RK_15, could you elaborate please, I do not understand why this is not copying the array and the inner object, I am mapping on array1 and piping each item through Object.create, which creates a new object with the same prototype/properties as the original object
– jo_va
Mar 8 at 10:17
@H_squared, I do not understand, could you elaborate please ?
– jo_va
Mar 8 at 10:18
@jo_va first the resultant object is not an array it is a plain object with numeric indexes second "Object.create" methods first argument is the new prototype for resultant object i.e. all the object properties will shift to its prototype. Just log the array2 before changing "myname" property and you will not see that property in the object because it is in prototype of that object.
– RK_15
Mar 8 at 10:20
|
show 6 more comments
Arrays and Objects are reference types, which means that when you make a copy by assignment, you are simply copying the reference and not the underlying array/object. In your case, when copying the array, you copy all of the object references, which will still point to the objects in your original array. You need to clone the objects too for it to work.
Use Array.map()
to iterate over your array and copy each item.
Use Object.create()
to make a shallow clone of each object. This function takes a prototype and property descriptors to create a new object. You can use Object.getPrototypeOf()
Object.getOwnPropertyDescriptors()
to pass it the prototype and property descriptors of your input object.
function OBJ1(name)
this.myname = name;
const array1 = [new OBJ1("NAME")];
const array2 = array1.map(obj =>
Object.create(
Object.getPrototypeOf(obj),
Object.getOwnPropertyDescriptors(obj)
)
);
array2[0].myname = 'Jack';
console.log(array1[0].myname);
console.log(array2[0].myname);
const array2 = array1.map(Object.create); Here you are creating two properties by name "myname" in object and its prototype.
– RK_15
Mar 8 at 10:12
this creates array2, but does not make a copy. Addthis.tags=tags
in your constructor, and you will see that the array in array2 is empty.
– H_squared
Mar 8 at 10:14
@RK_15, could you elaborate please, I do not understand why this is not copying the array and the inner object, I am mapping on array1 and piping each item through Object.create, which creates a new object with the same prototype/properties as the original object
– jo_va
Mar 8 at 10:17
@H_squared, I do not understand, could you elaborate please ?
– jo_va
Mar 8 at 10:18
@jo_va first the resultant object is not an array it is a plain object with numeric indexes second "Object.create" methods first argument is the new prototype for resultant object i.e. all the object properties will shift to its prototype. Just log the array2 before changing "myname" property and you will not see that property in the object because it is in prototype of that object.
– RK_15
Mar 8 at 10:20
|
show 6 more comments
Arrays and Objects are reference types, which means that when you make a copy by assignment, you are simply copying the reference and not the underlying array/object. In your case, when copying the array, you copy all of the object references, which will still point to the objects in your original array. You need to clone the objects too for it to work.
Use Array.map()
to iterate over your array and copy each item.
Use Object.create()
to make a shallow clone of each object. This function takes a prototype and property descriptors to create a new object. You can use Object.getPrototypeOf()
Object.getOwnPropertyDescriptors()
to pass it the prototype and property descriptors of your input object.
function OBJ1(name)
this.myname = name;
const array1 = [new OBJ1("NAME")];
const array2 = array1.map(obj =>
Object.create(
Object.getPrototypeOf(obj),
Object.getOwnPropertyDescriptors(obj)
)
);
array2[0].myname = 'Jack';
console.log(array1[0].myname);
console.log(array2[0].myname);
Arrays and Objects are reference types, which means that when you make a copy by assignment, you are simply copying the reference and not the underlying array/object. In your case, when copying the array, you copy all of the object references, which will still point to the objects in your original array. You need to clone the objects too for it to work.
Use Array.map()
to iterate over your array and copy each item.
Use Object.create()
to make a shallow clone of each object. This function takes a prototype and property descriptors to create a new object. You can use Object.getPrototypeOf()
Object.getOwnPropertyDescriptors()
to pass it the prototype and property descriptors of your input object.
function OBJ1(name)
this.myname = name;
const array1 = [new OBJ1("NAME")];
const array2 = array1.map(obj =>
Object.create(
Object.getPrototypeOf(obj),
Object.getOwnPropertyDescriptors(obj)
)
);
array2[0].myname = 'Jack';
console.log(array1[0].myname);
console.log(array2[0].myname);
function OBJ1(name)
this.myname = name;
const array1 = [new OBJ1("NAME")];
const array2 = array1.map(obj =>
Object.create(
Object.getPrototypeOf(obj),
Object.getOwnPropertyDescriptors(obj)
)
);
array2[0].myname = 'Jack';
console.log(array1[0].myname);
console.log(array2[0].myname);
function OBJ1(name)
this.myname = name;
const array1 = [new OBJ1("NAME")];
const array2 = array1.map(obj =>
Object.create(
Object.getPrototypeOf(obj),
Object.getOwnPropertyDescriptors(obj)
)
);
array2[0].myname = 'Jack';
console.log(array1[0].myname);
console.log(array2[0].myname);
edited Mar 8 at 10:43
answered Mar 8 at 10:05
jo_vajo_va
7,5332829
7,5332829
const array2 = array1.map(Object.create); Here you are creating two properties by name "myname" in object and its prototype.
– RK_15
Mar 8 at 10:12
this creates array2, but does not make a copy. Addthis.tags=tags
in your constructor, and you will see that the array in array2 is empty.
– H_squared
Mar 8 at 10:14
@RK_15, could you elaborate please, I do not understand why this is not copying the array and the inner object, I am mapping on array1 and piping each item through Object.create, which creates a new object with the same prototype/properties as the original object
– jo_va
Mar 8 at 10:17
@H_squared, I do not understand, could you elaborate please ?
– jo_va
Mar 8 at 10:18
@jo_va first the resultant object is not an array it is a plain object with numeric indexes second "Object.create" methods first argument is the new prototype for resultant object i.e. all the object properties will shift to its prototype. Just log the array2 before changing "myname" property and you will not see that property in the object because it is in prototype of that object.
– RK_15
Mar 8 at 10:20
|
show 6 more comments
const array2 = array1.map(Object.create); Here you are creating two properties by name "myname" in object and its prototype.
– RK_15
Mar 8 at 10:12
this creates array2, but does not make a copy. Addthis.tags=tags
in your constructor, and you will see that the array in array2 is empty.
– H_squared
Mar 8 at 10:14
@RK_15, could you elaborate please, I do not understand why this is not copying the array and the inner object, I am mapping on array1 and piping each item through Object.create, which creates a new object with the same prototype/properties as the original object
– jo_va
Mar 8 at 10:17
@H_squared, I do not understand, could you elaborate please ?
– jo_va
Mar 8 at 10:18
@jo_va first the resultant object is not an array it is a plain object with numeric indexes second "Object.create" methods first argument is the new prototype for resultant object i.e. all the object properties will shift to its prototype. Just log the array2 before changing "myname" property and you will not see that property in the object because it is in prototype of that object.
– RK_15
Mar 8 at 10:20
const array2 = array1.map(Object.create); Here you are creating two properties by name "myname" in object and its prototype.
– RK_15
Mar 8 at 10:12
const array2 = array1.map(Object.create); Here you are creating two properties by name "myname" in object and its prototype.
– RK_15
Mar 8 at 10:12
this creates array2, but does not make a copy. Add
this.tags=tags
in your constructor, and you will see that the array in array2 is empty.– H_squared
Mar 8 at 10:14
this creates array2, but does not make a copy. Add
this.tags=tags
in your constructor, and you will see that the array in array2 is empty.– H_squared
Mar 8 at 10:14
@RK_15, could you elaborate please, I do not understand why this is not copying the array and the inner object, I am mapping on array1 and piping each item through Object.create, which creates a new object with the same prototype/properties as the original object
– jo_va
Mar 8 at 10:17
@RK_15, could you elaborate please, I do not understand why this is not copying the array and the inner object, I am mapping on array1 and piping each item through Object.create, which creates a new object with the same prototype/properties as the original object
– jo_va
Mar 8 at 10:17
@H_squared, I do not understand, could you elaborate please ?
– jo_va
Mar 8 at 10:18
@H_squared, I do not understand, could you elaborate please ?
– jo_va
Mar 8 at 10:18
@jo_va first the resultant object is not an array it is a plain object with numeric indexes second "Object.create" methods first argument is the new prototype for resultant object i.e. all the object properties will shift to its prototype. Just log the array2 before changing "myname" property and you will not see that property in the object because it is in prototype of that object.
– RK_15
Mar 8 at 10:20
@jo_va first the resultant object is not an array it is a plain object with numeric indexes second "Object.create" methods first argument is the new prototype for resultant object i.e. all the object properties will shift to its prototype. Just log the array2 before changing "myname" property and you will not see that property in the object because it is in prototype of that object.
– RK_15
Mar 8 at 10:20
|
show 6 more comments
I think you need a deep cloning of your object. please use below function
function clone(src)
var ret=(src instanceof Array ? [] : );
for(var key in src)
if(!src.hasOwnProperty(key)) continue;
var val=src[key];
if(val && typeof(val)=='object') val=clone(val);
ret[key]=val;
return ret;
function OBJ1(name, tags)
this.myname = name;
this.mytags = tags;
this.myvalue = 0;
function OBJ2(arg1)
this.arg1 = arg1;
this.myarray = [];
var OBJ1_array = [];
var result_array2 = null;
var result;
OBJ1_array = createarray1();
for (i = 0; i < 2; i++)
result = createarray2();
function createarray1()
var myarray = [];
myarray.push(new OBJ1("NAME", [1, 2, 3]));
myarray.push(new OBJ1("others", [1, 2, 3]));
myarray.push(new OBJ1("total", [1, 2, 3]));
return myarray;
function createarray2()
var newarray = clone(OBJ1_array) ; // newarray should refer to a new array, not the same one as OBJ1_array
OBJ1_array[0].myname = "CHANGED";
console.log("categories", JSON.parse(JSON.stringify(OBJ1_array)));
console.log("newarray", JSON.parse(JSON.stringify(newarray)));
Much Simpler Approach
var cloneOfOBJ1_array = JSON.parse(JSON.stringify(OBJ1_array));
Does not copy methods. in my actual code, my Object contains methods.
– H_squared
Mar 8 at 11:33
@H_squared put your exact requirement in question
– Negi Rox
Mar 8 at 12:58
add a comment |
I think you need a deep cloning of your object. please use below function
function clone(src)
var ret=(src instanceof Array ? [] : );
for(var key in src)
if(!src.hasOwnProperty(key)) continue;
var val=src[key];
if(val && typeof(val)=='object') val=clone(val);
ret[key]=val;
return ret;
function OBJ1(name, tags)
this.myname = name;
this.mytags = tags;
this.myvalue = 0;
function OBJ2(arg1)
this.arg1 = arg1;
this.myarray = [];
var OBJ1_array = [];
var result_array2 = null;
var result;
OBJ1_array = createarray1();
for (i = 0; i < 2; i++)
result = createarray2();
function createarray1()
var myarray = [];
myarray.push(new OBJ1("NAME", [1, 2, 3]));
myarray.push(new OBJ1("others", [1, 2, 3]));
myarray.push(new OBJ1("total", [1, 2, 3]));
return myarray;
function createarray2()
var newarray = clone(OBJ1_array) ; // newarray should refer to a new array, not the same one as OBJ1_array
OBJ1_array[0].myname = "CHANGED";
console.log("categories", JSON.parse(JSON.stringify(OBJ1_array)));
console.log("newarray", JSON.parse(JSON.stringify(newarray)));
Much Simpler Approach
var cloneOfOBJ1_array = JSON.parse(JSON.stringify(OBJ1_array));
Does not copy methods. in my actual code, my Object contains methods.
– H_squared
Mar 8 at 11:33
@H_squared put your exact requirement in question
– Negi Rox
Mar 8 at 12:58
add a comment |
I think you need a deep cloning of your object. please use below function
function clone(src)
var ret=(src instanceof Array ? [] : );
for(var key in src)
if(!src.hasOwnProperty(key)) continue;
var val=src[key];
if(val && typeof(val)=='object') val=clone(val);
ret[key]=val;
return ret;
function OBJ1(name, tags)
this.myname = name;
this.mytags = tags;
this.myvalue = 0;
function OBJ2(arg1)
this.arg1 = arg1;
this.myarray = [];
var OBJ1_array = [];
var result_array2 = null;
var result;
OBJ1_array = createarray1();
for (i = 0; i < 2; i++)
result = createarray2();
function createarray1()
var myarray = [];
myarray.push(new OBJ1("NAME", [1, 2, 3]));
myarray.push(new OBJ1("others", [1, 2, 3]));
myarray.push(new OBJ1("total", [1, 2, 3]));
return myarray;
function createarray2()
var newarray = clone(OBJ1_array) ; // newarray should refer to a new array, not the same one as OBJ1_array
OBJ1_array[0].myname = "CHANGED";
console.log("categories", JSON.parse(JSON.stringify(OBJ1_array)));
console.log("newarray", JSON.parse(JSON.stringify(newarray)));
Much Simpler Approach
var cloneOfOBJ1_array = JSON.parse(JSON.stringify(OBJ1_array));
I think you need a deep cloning of your object. please use below function
function clone(src)
var ret=(src instanceof Array ? [] : );
for(var key in src)
if(!src.hasOwnProperty(key)) continue;
var val=src[key];
if(val && typeof(val)=='object') val=clone(val);
ret[key]=val;
return ret;
function OBJ1(name, tags)
this.myname = name;
this.mytags = tags;
this.myvalue = 0;
function OBJ2(arg1)
this.arg1 = arg1;
this.myarray = [];
var OBJ1_array = [];
var result_array2 = null;
var result;
OBJ1_array = createarray1();
for (i = 0; i < 2; i++)
result = createarray2();
function createarray1()
var myarray = [];
myarray.push(new OBJ1("NAME", [1, 2, 3]));
myarray.push(new OBJ1("others", [1, 2, 3]));
myarray.push(new OBJ1("total", [1, 2, 3]));
return myarray;
function createarray2()
var newarray = clone(OBJ1_array) ; // newarray should refer to a new array, not the same one as OBJ1_array
OBJ1_array[0].myname = "CHANGED";
console.log("categories", JSON.parse(JSON.stringify(OBJ1_array)));
console.log("newarray", JSON.parse(JSON.stringify(newarray)));
Much Simpler Approach
var cloneOfOBJ1_array = JSON.parse(JSON.stringify(OBJ1_array));
function clone(src)
var ret=(src instanceof Array ? [] : );
for(var key in src)
if(!src.hasOwnProperty(key)) continue;
var val=src[key];
if(val && typeof(val)=='object') val=clone(val);
ret[key]=val;
return ret;
function OBJ1(name, tags)
this.myname = name;
this.mytags = tags;
this.myvalue = 0;
function OBJ2(arg1)
this.arg1 = arg1;
this.myarray = [];
var OBJ1_array = [];
var result_array2 = null;
var result;
OBJ1_array = createarray1();
for (i = 0; i < 2; i++)
result = createarray2();
function createarray1()
var myarray = [];
myarray.push(new OBJ1("NAME", [1, 2, 3]));
myarray.push(new OBJ1("others", [1, 2, 3]));
myarray.push(new OBJ1("total", [1, 2, 3]));
return myarray;
function createarray2()
var newarray = clone(OBJ1_array) ; // newarray should refer to a new array, not the same one as OBJ1_array
OBJ1_array[0].myname = "CHANGED";
console.log("categories", JSON.parse(JSON.stringify(OBJ1_array)));
console.log("newarray", JSON.parse(JSON.stringify(newarray)));
function clone(src)
var ret=(src instanceof Array ? [] : );
for(var key in src)
if(!src.hasOwnProperty(key)) continue;
var val=src[key];
if(val && typeof(val)=='object') val=clone(val);
ret[key]=val;
return ret;
function OBJ1(name, tags)
this.myname = name;
this.mytags = tags;
this.myvalue = 0;
function OBJ2(arg1)
this.arg1 = arg1;
this.myarray = [];
var OBJ1_array = [];
var result_array2 = null;
var result;
OBJ1_array = createarray1();
for (i = 0; i < 2; i++)
result = createarray2();
function createarray1()
var myarray = [];
myarray.push(new OBJ1("NAME", [1, 2, 3]));
myarray.push(new OBJ1("others", [1, 2, 3]));
myarray.push(new OBJ1("total", [1, 2, 3]));
return myarray;
function createarray2()
var newarray = clone(OBJ1_array) ; // newarray should refer to a new array, not the same one as OBJ1_array
OBJ1_array[0].myname = "CHANGED";
console.log("categories", JSON.parse(JSON.stringify(OBJ1_array)));
console.log("newarray", JSON.parse(JSON.stringify(newarray)));
edited Mar 8 at 10:47
answered Mar 8 at 10:34
Negi RoxNegi Rox
1,8861511
1,8861511
Does not copy methods. in my actual code, my Object contains methods.
– H_squared
Mar 8 at 11:33
@H_squared put your exact requirement in question
– Negi Rox
Mar 8 at 12:58
add a comment |
Does not copy methods. in my actual code, my Object contains methods.
– H_squared
Mar 8 at 11:33
@H_squared put your exact requirement in question
– Negi Rox
Mar 8 at 12:58
Does not copy methods. in my actual code, my Object contains methods.
– H_squared
Mar 8 at 11:33
Does not copy methods. in my actual code, my Object contains methods.
– H_squared
Mar 8 at 11:33
@H_squared put your exact requirement in question
– Negi Rox
Mar 8 at 12:58
@H_squared put your exact requirement in question
– Negi Rox
Mar 8 at 12:58
add a comment |
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));
Answer copy pasted from somewhere else. Plus I've tried this and it didn't workas mentioned in the original post.
– H_squared
Mar 8 at 10:17
add a comment |
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));
Answer copy pasted from somewhere else. Plus I've tried this and it didn't workas mentioned in the original post.
– H_squared
Mar 8 at 10:17
add a comment |
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));
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));
answered Mar 8 at 9:58
Med ElhaddadMed Elhaddad
11
11
Answer copy pasted from somewhere else. Plus I've tried this and it didn't workas mentioned in the original post.
– H_squared
Mar 8 at 10:17
add a comment |
Answer copy pasted from somewhere else. Plus I've tried this and it didn't workas mentioned in the original post.
– H_squared
Mar 8 at 10:17
Answer copy pasted from somewhere else. Plus I've tried this and it didn't workas mentioned in the original post.
– H_squared
Mar 8 at 10:17
Answer copy pasted from somewhere else. Plus I've tried this and it didn't workas mentioned in the original post.
– H_squared
Mar 8 at 10:17
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55060656%2fcopy-array-of-objects%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
A good article with possible ways: medium.com/@Farzad_YZ/…
– harish sharma
Mar 8 at 10:00
Possible duplicate of How do I correctly clone a JavaScript object?
– cнŝdk
Mar 8 at 10:05