Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
43
rated 0 times [  47] [ 4]  / answers: 1 / hits: 35300  / 7 Years ago, wed, march 1, 2017, 12:00:00

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?


More From » jquery

 Answers
31

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







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




[#58725] Monday, February 27, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
alejandro

Total Points: 231
Total Questions: 102
Total Answers: 107

Location: Jordan
Member since Wed, Jun 17, 2020
4 Years ago
alejandro questions
Mon, Jul 18, 22, 00:00, 2 Years ago
Fri, Sep 18, 20, 00:00, 4 Years ago
Thu, Sep 10, 20, 00:00, 4 Years ago
;