如何克隆Javascript对象数组? [英] How to clone a Javascript Array of Objects?

查看:153
本文介绍了如何克隆Javascript对象数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结果集,它是一个对象数组。我需要克隆它,以便我可以对其进行更改,而不会触及原始数据。

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

在这个例子中,我创建了一个名为 data 并将其设置为源数据。

In this example, I created a variable called data and set it to my "Source Data".

我希望能够对这个新的数据变量进行更改,但看起来在更改它时,源数据正在被更改( w2ui.grid.records )。

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

有没有正确的方法来克隆这个集合,所以我可以有一个新的数据实例修改?

Is there a proper way to clone this set so I can have a new instance of the data to modify?

推荐答案

编辑

深度克隆使用 JSON.parse(JSON.stringify(arr));

浅层克隆使用 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);

这篇关于如何克隆Javascript对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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