How to replace the value of a property in an object using spread?

Asked

Viewed 56 times

0

I’m having a doubt in an exercise since yesterday and I can’t find anything on the net. The problem is this: I need to change the value of the CITY property and put another name on it, but when I try to change it, it rewrites the address field leaving only the value I tried to change.

Code below to contextualize:

const usuario = { nome: "Rafael", idade: 17, 
   endereco: { cidade: "Guatapará", uf: "SP", pais: "Brasil" }
};

const usuario2 = { ...usuario, endereco: { cidade: "Ribeirão Preto" } };

What I hope to get is this:

{ nome: 'Rafael', idade: 19, endereco: { cidade: "Ribeirão Preto", uf: "SP", pais: "Brasil" }}

But what I get is:

{ nome: 'Rafael', idade: 19, endereco: { cidade: 'Ribeirão' }}

As you can see, inside the address property only remained the city. How can I correct this?

1 answer

3


What’s going on:

When you use the spread on the object, you receive a new object with the same properties and values, {...usuario} return the same value.

When using the second property, you are adding or replacing. endereco: { cidade: "Ribeirão Preto" } replaces the property endereco with the object { cidade: "Ribeirão Preto" }, and that’s what you get.

Alternative:

If your exercise requires you to resolve through spread, one solution is to make the address also a "copy" of the original address:

const usuario2 = { ...usuario, endereco: { ...usuario.endereco, cidade: "Ribeirão Preto" } }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.