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?













1















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?










share|improve this question
























  • 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















1















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?










share|improve this question
























  • 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













1












1








1








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?










share|improve this question
















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






share|improve this question















share|improve this question













share|improve this question




share|improve this question








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

















  • 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












6 Answers
6






active

oldest

votes


















4














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.



demonstration image



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>








share|improve this answer

























  • Additional reading material: webreflection.co.uk/blog/2015/10/06/…

    – 3limin4t0r
    Mar 8 at 19:23


















1














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)));






share|improve this answer
































    0














    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)








    share|improve this answer

























    • 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











    • Does not copy methods. in my actual code, my Object contains methods.

      – H_squared
      Mar 8 at 11:33


















    0














    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);








    share|improve this answer

























    • 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











    • @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



















    0














    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));





    share|improve this answer

























    • 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


















    -1














    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));





    share|improve this answer























    • 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










    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
    );



    );













    draft saved

    draft discarded


















    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









    4














    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.



    demonstration image



    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>








    share|improve this answer

























    • Additional reading material: webreflection.co.uk/blog/2015/10/06/…

      – 3limin4t0r
      Mar 8 at 19:23















    4














    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.



    demonstration image



    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>








    share|improve this answer

























    • Additional reading material: webreflection.co.uk/blog/2015/10/06/…

      – 3limin4t0r
      Mar 8 at 19:23













    4












    4








    4







    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.



    demonstration image



    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>








    share|improve this answer















    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.



    demonstration image



    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>






    share|improve this answer














    share|improve this answer



    share|improve this answer








    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

















    • 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













    1














    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)));






    share|improve this answer





























      1














      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)));






      share|improve this answer



























        1












        1








        1







        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)));






        share|improve this answer















        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)));







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 8 at 10:30

























        answered Mar 8 at 10:19









        Zulqarnain JalilZulqarnain Jalil

        433520




        433520





















            0














            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)








            share|improve this answer

























            • 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











            • Does not copy methods. in my actual code, my Object contains methods.

              – H_squared
              Mar 8 at 11:33















            0














            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)








            share|improve this answer

























            • 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











            • Does not copy methods. in my actual code, my Object contains methods.

              – H_squared
              Mar 8 at 11:33













            0












            0








            0







            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)








            share|improve this answer















            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)






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Mar 8 at 10:28

























            answered Mar 8 at 9:59









            dporechnydporechny

            50229




            50229












            • 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











            • 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











            • @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











            0














            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);








            share|improve this answer

























            • 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











            • @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
















            0














            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);








            share|improve this answer

























            • 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











            • @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














            0












            0








            0







            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);








            share|improve this answer















            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);






            share|improve this answer














            share|improve this answer



            share|improve this answer








            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. 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











            • @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











            • 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











            • @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












            0














            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));





            share|improve this answer

























            • 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















            0














            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));





            share|improve this answer

























            • 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













            0












            0








            0







            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));





            share|improve this answer















            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)));






            share|improve this answer














            share|improve this answer



            share|improve this answer








            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

















            • 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











            -1














            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));





            share|improve this answer























            • 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















            -1














            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));





            share|improve this answer























            • 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













            -1












            -1








            -1







            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));





            share|improve this answer













            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));






            share|improve this answer












            share|improve this answer



            share|improve this answer










            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

















            • 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

















            draft saved

            draft discarded
















































            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.




            draft saved


            draft discarded














            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





















































            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







            Popular posts from this blog

            Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme

            Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

            2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived