Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

122
Visualizações
How to the get the sum of all the field with the same name in a nested array?

I'm trying to find the sum of all the field values of the nested array, I suck at explaining stuffs like this, I hope the code below will give you some insight of what I want to do.

The array looks like this

data = [
    {
        id: 8434,
        name: listName, 
        data: [
            {name: "a name",
             quantity: 20,
            }
            {name: "another name",
             quantity: 40,
            }
            {name: "another new name",
             quantity: 40,
            }
        ]
    }, 
    {
        id: 54343,
        name: "new list name", 
        data: [
            {name: "a name",
             quantity: 12,
            }
            {name: "another name",
             quantity: 10,
            }
            {name: "another new name",
             quantity: 16,
            }
        ]
    }
]

This is how I want the data to be after carrying out the sum

transformed = [
{name: "a name", quantity: 32},
{name: "another name", quantity: 50},
{name: "another new name", quantity: 56}
]
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can use Array.flatMap() followed by Array.reduce() to get the desired result.

We start by calling .flatMap() to get all the data values, then calling .reduce() on these to sum each value by name.

This will create an object, with a property for each name, we then call Object.values() to return to an array.

const data = [ { id: 8434, name: 'listName', data: [ { name: "a name", quantity: 20, }, { name: "another name", quantity: 40, }, { name: "another new name", quantity: 40, } ] }, { id: 54343, name: "new list name", data: [ { name: "a name", quantity: 12, }, { name: "another name", quantity: 10, }, { name: "another new name", quantity: 16, } ] } ];

const transformed = Object.values(data.flatMap(({ data }) => data).reduce((acc, { name , quantity }) => { 
    acc[name] = acc[name] || { name, quantity: 0 };
    acc[name].quantity += quantity;
    return acc;
}, {}))

console.log('Transformed:', transformed)
.as-console-wrapper { max-height: 100% !important; }

about 4 years ago · Juan Pablo Isaza Relatório

0

const transform = (data) => {
  const quantitySum = new Map()
  
  data.forEach(list => {
    list.data.forEach(({ name, quantity }) => {
      if (quantitySum.has(name)) {
        quantitySum.set(name, quantitySum.get(name) + quantity)
      } else {
        quantitySum.set(name, quantity)
      }
    })
  })
  
  return Array.from(quantitySum.entries())
    .map(([name, sum]) => ({
    name,
    quantity: sum
  }))
}
about 4 years ago · Juan Pablo Isaza Relatório

0

just loop them through and create a new object..

const data = [
    {
        id: 8434,
        name: 'listName', 
        data: [
            {
                name: "a name",
                quantity: 20,
            },
            {
                name: "another name",
                quantity: 40,
            },
            {
                name: "another new name",
                quantity: 40,
            }
        ]
    }, 
    {
        id: 54343,
        name: "new list name", 
        data: [
            {
                name: "a name",
                quantity: 12,
            },
            {
                name: "another name",
                quantity: 10,
            },
            {
                name: "another new name",
                quantity: 16,
            }
        ]
    }
]


// Logic:
const transformed = []

data.forEach(d => {
    d.data.forEach(item => {
        const exist = transformed.find(t => t.name == item.name)
        if(exist) 
            exist.quantity += item.quantity
        else 
            transformed.push(item)
    })
})

console.log(transformed)

Output:

[
  { name: 'a name', quantity: 32 },
  { name: 'another name', quantity: 50 },
  { name: 'another new name', quantity: 56 }
]
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda