Adding values for equal properties to an object

Asked

Viewed 49 times

0

I would like to know how to add values to a "property", when an array displays different values for the second "property" and the same value for the first "property".

For example:

Entree:

array1: {
  {nome: joao, sobrenome: silva},
  {nome: claudio, sobrenome: silva},
  {nome: jose, sobrenome: oliveira},
  {nome: joao, sobrenome: costa}
} 

Exit:

array2: {
  {nome: joao, sobrenome: [silva, costa]},
  {nome: claudio, sobrenome: silva},
  {nome: jose, sobrenome: oliveira}
} 

1 answer

1


You can create a new object in a cycle where you iterate the elements of the initial array. With each iteration of the cycle you can check whether the object you are creating already has that key.

I suggest however being consistent and always having the last name with the type Array, so you don’t need to check later if it is String or Array.

I would do it like this:

const nomes = [{
    nome: 'joao',
    sobrenome: 'silva'
  },
  {
    nome: 'claudio',
    sobrenome: 'silva'
  },
  {
    nome: 'jose',
    sobrenome: 'oliveira'
  },
  {
    nome: 'joao',
    sobrenome: 'costa'
  }
];

const organizados = nomes.reduce((obj, pessoa) => {
  const nome = pessoa.nome;
  const sobrenomes = obj[nome] ? obj[nome].sobrenome : [];
  return {
    ...obj,
    [nome]: {
      nome,
      sobrenome: [...sobrenomes, pessoa.sobrenome]
    }
  };
}, {});

console.log(organizados);

To do it like you said in the comment you can do it like this:

const nomes = [{
    nome: 'joao',
    sobrenome: 'silva'
  },
  {
    nome: 'claudio',
    sobrenome: 'silva'
  },
  {
    nome: 'jose',
    sobrenome: 'oliveira'
  },
  {
    nome: 'joao',
    sobrenome: 'costa'
  }
];

const organizados = nomes.reduce((obj, pessoa) => {
  const {nome, sobrenome} = pessoa;
  if (!obj[nome]) obj[nome] = {nome};
  obj[nome][sobrenome] = 1;
  return obj;
}, {});
const array = Object.keys(organizados).map(nome => organizados[nome]);

console.log(array);

  • Could you help me understand how things are going, especially Return? Because I want to generate a different output that actually looks like this: array: { {name:Joao, silva:1, costa:1}, {name:Claudio, silva:1}... }, I need to know how many times Joao appeared as silva or another last name.

  • @Magno is always better to ask the question exactly what you are looking for. So you don’t waste time or who answers :) I edited the answer, see if you understand better how it works and if you do what you want...

  • Perfect, Sergio I do not ask exactly what I want because I like trying to solve the problem, as I was struggling to know how to group the surnames asked only that. For example, instead of 1 it was to put the amount of times that the same last name appeared, but that I know how to do, so it looks like I did something tbm, haha. Thank you.

Browser other questions tagged

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