skip to Main Content

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


  1. Spread operator (…) makes a shallow copy which means both the original and copy refers to the same memory location. Try this

    var users = [{userName: 'abc', userUID: 'abc'}, {userName: 'def', userUID: 'def'}];
    var list = JSON.parse(JSON.stringify(users));
    var listModified = list.map(x => x.userUID === 'abc' ? '' : x.userName);
    Login or Signup to reply.
  2. 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);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search