Repeated ID on objects in my array

Asked

Viewed 33 times

0

I’m trying to assign an ID to each object in my array, but when I have two or more similar objects, they end up getting the same ID. I’ve tried to do indexOf() and also did not work.

this.selection.selected.forEach(servico => {
   servico.id = this.contador;
   this.adicionados.push(servico);
   this.contador++;
});

Lista com objetos diferentes Lista com 1 objeto repetido

List with different objects - List with 1 repeated object

1 answer

0

As I understand it, they’re repeated because you keep adding to the same array without clearing it first.

See if the following code solves your problem

const novosAdicionados = [];
this.selection.selected.forEach(servico => {
    servico.id = this.contador;
    novosAdicionados.push(servico);
    this.contador++;
 });

 this.adicionados = novosAdicionados;

If not, you need more information/code to help you.

Browser other questions tagged

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