How to clone a Javascript Array of Objects?
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>
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);
ES6:
If you want to have cloned objects too, you have to spread array and objects:
const newArrayOfObjects = [
...originalArrayOfObject
].map(i => ({ ...i}));