将对象数组复制到 javascript 中的另一个数组中(深度复制) [英] Copying an array of objects into another array in javascript (Deep Copy)

查看:128
本文介绍了将对象数组复制到 javascript 中的另一个数组中(深度复制)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 javascript 中使用 slice(0) 和 concat() 将对象数组复制到另一个数组中不起作用.

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.

推荐答案

尝试

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

这篇关于将对象数组复制到 javascript 中的另一个数组中(深度复制)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆