Skip to content
Advertisement

Why does the copy of an array using the spread operator when run through map modify the original array?

  1. Why does the copy of an array using the spread operator when run through map modify the original array?

  2. 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 "")

Answer

The 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.

Advertisement