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.
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);
Since you are using jquery you can try 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>
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).
If you need a deep clone, because your array contains objects/arrays too, try this...
https://github.com/pvorb/clone
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:
https://www.npmjs.com/package/lodash.clonedeep
ES6:
If you want to have cloned objects too, you have to spread array and objects:
const newArrayOfObjects = [
...originalArrayOfObject
].map(i => ({ ...i}));
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);