Why does the copy of an array using the spread operator when run through map modify the original array?
What should i do here to not mutate the original array?
const data = {hello : "10"};
const prop = [{name : "hello", color: "red", value : ""}]
const copyProp = [ ...prop ]
copyProp.map(el => {
el.value = data[el.name] || ""
return el
}) //
console.log(copyProp === prop) // -> false
console.log(copyProp) // -> value: 10
console.log(prop) // -> Value: 10 (Should still be "")
Why does the copy of an array using the spread operator when run through map modify the original array?
What should i do here to not mutate the original array?
const data = {hello : "10"};
const prop = [{name : "hello", color: "red", value : ""}]
const copyProp = [ ...prop ]
copyProp.map(el => {
el.value = data[el.name] || ""
return el
}) //
console.log(copyProp === prop) // -> false
console.log(copyProp) // -> value: 10
console.log(prop) // -> Value: 10 (Should still be "")
Share
Improve this question
edited Jun 10, 2020 at 20:51
Terry
asked Jun 10, 2020 at 20:49
TerryTerry
1,7115 gold badges26 silver badges45 bronze badges
1
- You're copying the array. You're not copying the objects that you mutate. – Bergi Commented Jun 10, 2020 at 20:59
2 Answers
Reset to default 5The spread operator creates shallow copy of the array. In other words, you create a new array with references to the same objects. So when you modify those objects, the changes are reflected in the original array.
In general, when you need copy an array, you should consider making a deep copy. However, in this case, you just need to use map()
correctly. map()
creates a new array, so it can make the modified copy for you directly:
const copyProps = props.map(el => {
return {
...el,
value: data[el.name] || '',
}
});
Here I copy each object using the spread operator. This means the resulting array has its own references of objects. This has the same caveat as your original solution: this is a shallow copy. For your example data, it is fine because all values and keys are strings. However, if your real data is more deeply nested with more arrays and objects, you will encounter the same problem.
Both arrays and objects are passed by reference, so when you spread an array you create new array but fill it with references to original objects and when you modify those objects in the new array you still modify the same data in memory that is referenced in both arrays.
Also map method will always return new array so in this case you only need to clone objects and since here you do not have deeply nested objects you can use object spread syntax.
const data = {
hello: "10"
};
const prop = [{
name: "hello",
color: "red",
value: ""
}]
const copyProp = prop.map(el => ({ ...el,
value: data[el.name] || ''
}))
console.log(copyProp)
console.log(prop)