0

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

David
  • 208,112
  • 36
  • 198
  • 279
user10863293
  • 770
  • 4
  • 11
  • 32
  • Please add a [mre]. – 0stone0 Jul 27 '23 at 16:04
  • But `map` makes a new array with the returned value, right now you only return an empty string or the username, not the complete user object. – 0stone0 Jul 27 '23 at 16:05
  • @0stone0 Yeah I know but that's what I want to do but it changes also the value of my users but it shouldn't – user10863293 Jul 27 '23 at 16:07
  • Note that this has nothing to do with React. What you're showing is plain JavaScript, unrelated to any framework. – David Jul 27 '23 at 16:11
  • You could clone each entry, via `Object.assign({}, x)`and return the modified clone? Also there are other coding errors as pointed out by @0stone0 Also as opinion: avoid single letter variables – Andre M Aug 18 '23 at 17:50

1 Answers1

0

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:

var list = JSON.parse(JSON.stringify(users));
var listModified = list.map(x => x.userUID === 'azeaz-azeze-azeaze' ? { ...x, userName: '' } : x);

Another option is to use spread operator with map()::

var list = users.map(obj => ({ ...obj }));
var listModified = list.map(x => x.userUID === 'azeaz-azeze-azeaze' ? { ...x, userName: '' } : x);
Sangam Belose
  • 4,262
  • 8
  • 26
  • 48