How can I change a value taken from the array without modifying the array itself?

Viewed 47

I need to extract a value from this array and use it inside a variable. but then if I log array I see the user one now is Julian. How do I avoid it?

let array = [{'id':'1','name':'User one','phone': '+51 111 222 333'},'id':'2','name':'User two','phone': '+51 111 222 333'}, 'id':'3','name':'User Three','phone': '+51 111 222 333'}];

I do:

 let user = array[0];
 user.name = "Julian"
2 Answers

You can use the spread operator ... to create a "duplicate" of the object that can be modified without changing the original.

Remember that array contains references to objects. By doing let user = array[0], you are assigning user to the same reference as array[0]. Both point to the same object, and changes done through one can be seen with the other. However, by using ..., you can put all the key-value pairs from the object stored in array[0] into a new object that can be modified independently.

let array = [
  {'id':'1',
  'name':'User one',
  'phone': '+51 111 222 333'
  },
  {'id':'2',
  'name':'User two',
  'phone': '+51 111 222 333'
  }, 
  {
  'id':'3',
  'name':'User Three',
  'phone': '+51 111 222 333'
  }
]


let user = {...array[0]}
user.name = "Julian"

console.log(user)
console.log(array[0])

You have to copy the object so it has it's own reference in memory so you can use Object.assign to create a new Object

let array = [{'id':'1','name':'User one','phone': '+51 111 222 333'},{'id':'2','name':'User two','phone': '+51 111 222 333'},{ 'id':'3','name':'User Three','phone': '+51 111 222 333'}];

   const ob=Object.assign({},array[0])
   ob.name="Julian"
   console.log(array)

alternatively you can use the spread operator

let array = [{'id':'1','name':'User one','phone': '+51 111 222 333'},{'id':'2','name':'User two','phone': '+51 111 222 333'},{ 'id':'3','name':'User Three','phone': '+51 111 222 333'}];

   const ob={...array[0]}
   ob.name="Julian"
   console.log(array)
   console.log(ob)

Related