Solution
const arr = [{a: 1}]
const copy = arr.map(item => ({...item}))
Explanation:
it sounds like a reference problem. ( shallow copy vs deep clone )
first of all, let's see how references work.
const arr = [{a: 1}]
const copy = arr // we assign copy as refernce to arr
copy.push({b:2}) // push item to copy array.
console.log(arr) // [{a: 1}, {b: 2}]
console.log(copy) // [{a: 1}, {b: 2}]
ok so we want to clone the array, but we want to create a new array (shallow copy).
const arr = [{a: 1}]
const copy = Array.from(arr) // return shallow-copied, [ref][1]
copy.push({b:2})
console.log(arr) // [{a: 1}]
console.log(copy) // [{a: 1}, {b: 2}]
but the problem is Array and Object either store by reference so when you clone(shallow) the array the objects inside are store by reference. that means, even you clone the array and create a new array, the objects inside copy with the same reference.
let's look on example.
const arr = [{a: 1}]
const copy = Array.from(arr)
copy.push({b:2})
copy[0].a = 3
console.log(arr) // [{a: 3}]
console.log(copy) // [{a: 3}, {b: 2}]
You can see it's not the same array, but the objects are the same ( by reference )
so you need deep copy and not shallow, you can read about that here
You can use lodash to deep clone, deepClone method.
or you can use ES6
const arr = [{a: 1}]
const copy = arr.map(item => ({...item})) // ES5: arr.map(item => object.assign({}, item))
originalandmodified, initially both are same and after any operation you have to updatemodifiedone, on reset you can easily updatemodifiedwithoriginalObject.assignfor this - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…