Group objects by a certain angular key

Asked

Viewed 335 times

0

I have three objects:

0{
  conta: "teste",
  data: "01/01/2018"
},
1{
  conta: "teste",
  data: "01/03/2018"
}
2{
  conta: "teste2",
  data: "02/02/2019"
}

I need to group the objects that have the account with the same name, resulting in:

0{
  conta: "teste"{
   0   {
     data:01/01/2018
    },
   1{
     data:01/03/2018
    }
}
1{
conta: "teste2" {
    0{
       data: "02/02/2019"
    }
}

1 answer

3


to do with Array.reduce:

let entrada = [
    {
        conta: "teste1",
        data: "01/01/2018"
    },
    {
        conta: "teste1",
        data: "01/03/2018"
    },
    {
        conta: "teste2",
        data: "02/02/2019"
    }
];

let saida = entrada.reduce((retorno, dados) => { 
    retorno[dados.conta] = retorno[dados.conta] || []; 
    retorno[dados.conta].push({ data: dados.data });
    return retorno; 
}, {});


console.log ( saida );

or with Array.foreach

let entrada = [
    {
        conta: "teste1",
        data: "01/01/2018"
    },
    {
        conta: "teste1",
        data: "01/03/2018"
    },
    {
        conta: "teste2",
        data: "02/02/2019"
    }
];

let grupo = {};

entrada.forEach( ( valor ) => {
    grupo[valor.conta] = grupo[valor.conta]  || [];
    grupo[valor.conta].push({ data : valor.data });
});

console.log ( grupo );
  • That way I don’t get the object the way I expect. How I expect: (3) [{... }, {...}, {...}] How I get through this function: {nameConta1: Array(2),nameConta2: Array(1)}

  • That way I can’t iterate through an ngfor, because I would have to specify which account I want to loop from, and how that data varies, there’s no way I can fix it. Ex: *ngFor="Let pergunta of contas.teste1"

  • understood, is that your question was "how to group the data of the object", I will try to adjust

Browser other questions tagged

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