How to use ES6+ Spread to metamorphosize one object within another?

Asked

Viewed 48 times

-1

I have the following object below:

const usuario = {
      nome: 'Diego',
      idade: 23,
      endereco: {
        cidade: 'Rio do Sul',
        uf: 'SC',
        pais: 'Brasil',
      }
};

I’m gonna create a usuario2 based on the object usuario above, however, I will change the name to Gabriel

const usuario2 = { ...usuario, nome: 'Gabriel' };

succeeded.

Now I’m gonna try to create a usuario3, but changing the city to Lontras.

const usuario3 = { ...usuario, endereco: {cidade: 'Lontras'}};

did not succeed.

What’s the right way to do this metamorphosis, where I hold one object within another?

  • it was not very clear your problem, put the whole code with the expected result to be easier

1 answer

2

If you are to modify only one of the properties of an internal object, such as the endereco, you will have to deconstruct that internal object as well, otherwise you would just be overwriting the object endereco with another object that owns only the property you declared, in case, cidade. Example:

const usuario = {
  nome: 'Diego',
  idade: 23,
  endereco: {
    cidade: 'Rio do Sul',
    uf: 'SC',
    pais: 'Brasil',
  }
};

const usuario2 = { 
  ...usuario, 
  endereco: {
    ...usuario.endereco, 
    cidade: 'Lontras'
  }
};

console.log(usuario2);

Browser other questions tagged

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