Objects with equal name fields using scatter notation (spread Operator)

Asked

Viewed 25 times

1

Considering two objects (user and unit):

var user = {
    nome: 'Nome aqui',
    idade: 45
};

var unidade = {
    nome: 'Nome da unidade',
    idade: 22
};


// Spread Operador
var dadosGerais = {
    ...user,
    ...unidade
};

console.log(dadosGerais);

The output result is as follows:

Saída do código anterior no console das ferramentas de desenvolvedor do Google Chrome

Unable to use the spread when the field names are equal, in the case of, nome and idade that are repeated in user and unit?

If possible, how it should be done?

1 answer

2


It is not that you cannot use scattering notation on objects that contain names of equal properties. It can and is, in fact, being done.

The problem is that objects cannot have two properties with the same name. If this occurs, only the last property defined with the repeated name will be considered. The previous one will be silently overwritten. Let’s see:

const obj = {
  name: 'Old',
  age: 50,
  name: 'Foo'
};

console.log(obj);
console.log(obj.name); // Foo

Note that the property name was set twice. However, only the last, defined with value 'Foo' remained.

When you use scattering notation, the properties of each object are defined on the resulting object (I explain it better here) and thus, if there are properties with the same name, only the latter will be maintained.

If you need to create a new object with all values so that they are not lost, you should use different names. An alternative:

const user = {
  nome: 'Nome aqui',
  idade: 45
};

const unidade = {
  nome: 'Nome da unidade',
  idade: 22
};

const result = {
  ...user,
  unidade
};

console.log(result);

Browser other questions tagged

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