I copy my array with [...array]
and try to modify something inside but i don’t want to modify the original table but it modify my array also and I don’t understand why
var users = [{userUID : '123', userName : 'TOTO'},{userUID : '345', userName : 'TITI'},{userUID : '678', userName : 'TATA'}]
var list = [...users]
var listModifie = list.map(x => x.userName = x.userUID == '678' ? '' : x.userName)
console.log(users)
So what I want to do is copy the table get the data modify a specific data but not modify my users list
2
Answers
Spread operator (…) makes a shallow copy which means both the original and copy refers to the same memory location. Try this
The behavior you are experiencing is due to how JavaScript handles objects and arrays. The spread operator […array] creates a shallow copy of the original array, but it only copies the references to the objects within the array, not the objects themselves. As a result, the new array and the original array still point to the same objects in memory.
In your code, when you modify the userName property of the objects using list.map(), it affects both the original users array and the list array because they are both referencing the same objects.
One way to achieve this is by using JSON.parse() and JSON.stringify() to serialize and deserialize the array:
Another option is to use spread operator with map()::