Copying an array of objects into another array in javascript (Deep Copy)

46,199

Solution 1

Try

var copy = JSON.parse(JSON.stringify(tags));

Solution 2

Try the following

// Deep copy
var newArray = jQuery.extend(true, [], oldArray);

For more details check this question out What is the most efficient way to deep clone an object in JavaScript?

Solution 3

As mentioned Here .slice(0) will be effective in cloning the array with primitive type elements. However in your example tags array contains anonymous objects. Hence any changes to these objects in cloned array are reflected in tags array.

@dangh's reply above derefences these element objects and create new ones.

Here is another thread addressing similar situation

Solution 4

A nice way to clone an array of objects with ES6 is to use spread syntax:

const clonedArray = [...oldArray];

MDN

Solution 5

Easiest and the optimistic way of doing this in one single line is using Underscore/Lodash

let a = _.map(b, _.clone)

Share:
46,199
jsbisht
Author by

jsbisht

Updated on December 17, 2020

Comments

  • jsbisht
    jsbisht over 3 years

    Copying an array of objects into another array in javascript using slice(0) and concat() doesnt work.

    I have tried the following to test if i get the expected behaviour of deep copy using this. But the original array is also getting modified after i make changes in the copied array.

    var tags = [];
    for(var i=0; i<3; i++) {
        tags.push({
            sortOrder: i,
            type: 'miss'
        })
    }
    for(var tag in tags) { 
        if(tags[tag].sortOrder == 1) {
            tags[tag].type = 'done'
        }
    }
    console.dir(tags)
    
    var copy = tags.slice(0)
    console.dir(copy)
    
    copy[0].type = 'test'
    console.dir(tags)
    
    var another = tags.concat()
    another[0].type = 'miss'
    console.dir(tags)
    

    How can i do a deep copy of a array into another, so that the original array is not modified if i make a change in copy array.