Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
583 views
in Technique[技术] by (71.8m points)

jquery - How to clone a Javascript Array of Objects?

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 data and set it to my "Source 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).

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

EDIT

Deep clone use JSON.parse(JSON.stringify(arr));

Shallow clone Use slice(0);

var arr = [{'obj1':1}, {'obj2':2}];
var clone = arr.slice(0);
console.log(clone);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...