Copying an array of objects into another array in

2020-02-03 05:57发布

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.

9条回答
Emotional °昔
2楼-- · 2020-02-03 05:59

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?

查看更多
爷的心禁止访问
3楼-- · 2020-02-03 06:00

Same issue happen to me. I have data from service and save to another variable. When ever I update my array the copied array also updated. old code is like below

//$scope.MyData get from service
$scope.MyDataOriginal = $scope.MyData;

So when ever I change $scope.MyData also change $scope.MyDataOriginal. I found a solution that angular.copy right code as below

$scope.MyDataOriginal = angular.copy($scope.MyData);

查看更多
不美不萌又怎样
4楼-- · 2020-02-03 06:01

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

const clonedArray = [...oldArray];

MDN

查看更多
叼着烟拽天下
5楼-- · 2020-02-03 06:02

You just need to use the '...' notation.

// THE FOLLOWING LINE COPIES all elements of 'tags' INTO 'copy'
var copy = [...tags]

When you have an array say x, [...x] creates a new array with all the values of x. Be careful because this notation works slightly differently on objects. It splits the objects into all of its key, value pairs. So if you want to pass all the key value pairs of an object into a function you just need to pass function({...obj})

查看更多
乱世女痞
6楼-- · 2020-02-03 06:09

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

查看更多
叼着烟拽天下
7楼-- · 2020-02-03 06:15

Try

var copy = JSON.parse(JSON.stringify(tags));
查看更多
登录 后发表回答