2

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 2

3

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)

Sign up to request clarification or add additional context in comments.

3 Comments

I tried but I got an error: 78:21 error "ob" is not defined no-undef
It should work without variable declaration. However I have updated that, try it now and let me know if it works for you
It does. Thank you
3

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])

2 Comments

This is working on my laptop but not on my phone, its old, maybe thats why. Thanks
Strange. The phone being old is a likely explanation, the spread operator was introduced in ES6. Glad it worked though!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.