如何克隆一个 Javascript 对象数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42523881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to clone a Javascript Array of Objects?
提问by SBB
I have a result set which is an array of objects. I need to clone this so I can make changes to it, without touching the original data.
我有一个结果集,它是一个对象数组。我需要克隆它,以便我可以对其进行更改,而无需触及原始数据。
var data = w2ui.grid.records,
exclude = Array('recid', 'w2ui'); // Exclude these data points from the pivot
// Modify our tempData records to remove HTML
$.each(data, function(key, value) {
$.each(value, function(_key, _value) {
if(jQuery.inArray(_key, exclude) != -1) {
delete data[key][_key];
}else{
data[key][_key] = $('<div>'+_value+'</div>').text(); // <div></div> for those which are simply strings.
}
});
});
In this example, I created a variable called dataand set it to my "Source Data".
在此示例中,我创建了一个名为的变量data并将其设置为我的“源数据”。
I expected to be able to make changes to this new data variable but it appears that when making changes to it, the source data is being changed (w2ui.grid.records).
我希望能够对这个新数据变量进行更改,但似乎在对其进行更改时,源数据正在更改 ( w2ui.grid.records)。
Is there a proper way to clone this set so I can have a new instance of the data to modify?
有没有一种正确的方法来克隆这个集合,这样我就可以有一个新的数据实例来修改?
回答by zer00ne
EDIT
编辑
Deep clone use JSON.parse(JSON.stringify(arr));
深度克隆使用 JSON.parse(JSON.stringify(arr));
Shallow clone Use slice(0);
浅克隆使用 slice(0);
var arr = [{'obj1':1}, {'obj2':2}];
var clone = arr.slice(0);
console.log(clone);
var arr = [{'obj1':1}, {'obj2':2}]
var clone = JSON.parse(JSON.stringify(arr));
console.log(clone);
回答by Remownz
ES6:
ES6:
If you want to have cloned objects too, you have to spread array and objects:
如果你也想克隆对象,你必须传播数组和对象:
const newArrayOfObjects = [
...originalArrayOfObject
].map(i => ({ ...i}));
回答by Suchit kumar
Since you are using jquery you can try extend:
由于您使用的是 jquery,您可以尝试extend:
var arr = [{'obj1':1}, {'obj2':2}];
var clone = jQuery.extend(true, [], arr);
clone[0]['obj1']=10;
console.log(clone);
console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
回答by monners
Lodash has a method specifically for this called clonedeep. There's a standalone package for it if you don't want to pull in the entire library:
Lodash 有一个专门为此调用的方法clonedeep。如果你不想拉入整个库,有一个独立的包:
回答by WitVault
There are various ways to do it-
有多种方法可以做到——
let arr = [{
'obj1': 1
}, {
'obj2': 2
}];
// 1
const arr2 = arr.slice();
console.log(arr2);
// 2
const arr3 = [].concat(arr);
console.log(arr3);
// 3
// or use the new ES6 Spread
const arr4 = [...arr];
console.log(arr4);
// 4
const arr5 = Array.from(arr);
console.log(arr5);
回答by Rik Lewis
This is because an array is held as a pointer, so setting a new variable just points to the same array.
这是因为数组是作为指针保存的,所以设置一个新变量只是指向同一个数组。
The easiest way I know of is with slice...
我所知道的最简单的方法是切片...
var data = w2ui.grid.records.slice(0);
This creates a new array with all of the original values in, because you're slicing from the first one (0).
这将创建一个包含所有原始值的新数组,因为您是从第一个 (0) 开始切片。
If you need a deep clone, because your array contains objects/arrays too, try this...
如果你需要一个深度克隆,因为你的数组也包含对象/数组,试试这个......
回答by Arun Kumar
You can achieve this from ES6 spread operators
您可以通过 ES6 扩展运算符实现此目的
var arr1 = [1]
var arr2 = arr1
arr1 === arr2 //true
arr2.push(2)
arr2 //[1, 2]
arr1 //[1, 2]
var arr3 = [...arr1] //create a copy of existing array
arr1 === arr3 //false
arr2 === arr3 //false
arr3.push(3)
arr3 //[1, 2, 3]
arr1 //[1, 2]
arr2 //[1, 2]
Same syntax can be used for javascripts object as well
相同的语法也可用于 javascripts 对象
var newObj = [...existingObj]
var newObj = [...existingObj]

