Concatenate Object Array with length

Asked

Viewed 23 times

-2

Good night,

I have the following doubt, I have 2 arrays of objects being the first of cars and the second of sales, having the second one a relation through the car id. I wonder how I can concatenate the array below so it can look like the reported array.

carros = [
{
    id: 1,
    cor: "azul",
    marca: "vw"
}
{
    id: 2,
    cor: "vermelho",
    marca: "audi"
}
{
    id: 3,
    cor: "preto",
    marca: "ford"
}
]

vendas = [
{
    valor: "10",
    data: "22/05/2021",
    idCarro: 1
}
{
    valor: "30",
    data: "02/06/2021",
    idCarro: 1
}
{
    valor: "5",
    data: "17/08/2021",
    idCarro:3
}
]

relatorio = [
{
    id: 1,
    cor: "azul",
    marca: "vw",
    venda: 2
}
{
    id: 2,
    cor: "vermelho",
    marca: "audi",
    venda: 0
}
{
    id: 3,
    cor: "preto",
    marca: "ford",
    venda: 1
}
]

I tried to use the loops for and foreach with the Concat functions but the result is not expected, it adds as if it were a new car. I managed to partially do the form below, creating a foreach, but it stays as Object and breaks my ng-repeat loop of Angularjs that expects an Array.

vendas.forEach((item) =>{
              total = total + 1;
              rep.venda = total;
            }) 

relatorios = {... carros, ...rep}
  • I indicated two similar questions in the blue box above. Although it is not 100% exactly the same, in essence the problem is the same: to join two arrays that have a common information, in a third array (just adapt to your specific case). This is what I found in a quick search, but you can use the site search, as there must be numerous cases similar to yours - I suggest starting around here :-)

  • Complementing, now are 3 similar questions, and as already said, just see the solutions and adapt to your case :-)

  • Thanks for the @hkotsubo tip, I will check!

No answers

Browser other questions tagged

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