How to use destructuring assignment to build a new object with common attributes?

Asked

Viewed 25 times

0

I have an array with the following objects:

0: {nome: "Ricardo Graciolli", id: "2", atendimentos: "12", horario: "12:00"}
1: {nome: "Ana Paula Germano", id: "3", atendimentos: "12", horario: "07:00"}
2: {nome: "Ricardo Graciolli", id: "2", atendimentos: "15", horario: "07:00"}

And I would like a result that returns me an array more or less like this:

[{
        nome: "Ricardo Graciolli",
        id: "2",
        horarios: [{
            horario: "12:00",
            atendimentos: "16"
        }, {
            horario: "07:00",
            atendimentos: "12"
        }]
    },
    {
        nome: "Ana Paula Germano",
        id: "3",
        horarios: [{
            horario: "07:00",
            atendimentos: "12"
        }]
    }
]

1 answer

0


Need to use destructuring assignment? I think you need it, you don’t need it...

let dados = [
  {nome: "Ricardo Graciolli", id: "2", atendimentos: "12", horario: "12:00"},
  {nome: "Ana Paula Germano", id: "3", atendimentos: "12", horario: "07:00"},
  {nome: "Ricardo Graciolli", id: "2", atendimentos: "15", horario: "07:00"}
];

let result = {};
for (const dado of dados) {
    let obj_horario = { horario: dado.horario, atendimentos: dado.atendimentos };
    if (result[dado.id]) { // se já existe o id nos resultados, acrescenta os horários
        result[dado.id].horarios.push(obj_horario);
    } else { // se não existe o id nos resultados, cria um novo
        result[dado.id] = {
            nome: dado.nome, id: dado.id,
            horarios: [ obj_horario ]
        };
    }
}

result = Object.values(result);
console.log(result);

First you create an object whose keys will be the id’s, and the values are the objects you want to create (the one with name, id and time).

Then just see if the id already exists in the object. If it does not exist, it creates a new object. If it already exists, just add the new time in the existing one.

At the end, use Object.values to take only the values of the result. The result will be the array you want.

  • I was going to edit the title just for that! The destructuring assignment was the way I was thinking to solve the problem, but there’s really no need. Your answer was exactly what I was looking for. Thank you very much!

Browser other questions tagged

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