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

103
Visualizações
How to sum each value inside array of object to new variable

I have a data like this :

const fund = 
[
 {
  id: 1234,
  totalAmount: 0,
  data: 
   [
    {
     id: 1234,
     amount: '4.000'
    },
    {
     id: 1234,
     amount: '3.000'
    }
   ]
 },
 {
  id: 12345,
  totalAmount: 0
 },
 {
  id: 123456,
  totalAmount: 0
  data: 
   [
    {
     id: 123456,
     amount: '3.000'
    },
    {
     id: 123456,
     amount: '5.000'
    }
   ]
 }
]

I want to sum the amount inside of data each id to a key called totalAmount. But not all the parent id have data key.

here's my desired output :

const fund = 
[
 {
  id: 1234
  data: 
   [
    {
     id: 1234,
     amount: '4.000'
    },
    {
     id: 1234,
     amount: '3.000'
    }
   ],
  totalAmount: 7000
 },
 {
  id: 12345,
  totalAmount: 0        
 },
 {
  id: 123456,
  data: 
   [
    {
     id: 123456,
     amount: '3.000'
    },
    {
     id: 123456,
     amount: '5.000'
    }
   ],
  totalAmount: 8000
 }
]

I was trying with this code :

fund.forEach((elA, i) => {
        if (elA.data) {
          const total = funders[i].data.reduce((acc, curr) => {
            acc += parseInt(curr.amount.replace(/\./g, ''))
            return acc
          })
          fund[i] = total ? {...elA, totalAmount: total} : elA;
        }
      })

But it's not summing like i want.

Where's my mistake ?

Please ask me if you need more information if it's still not enough to solve that case.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You need to define the initial value for the reduce iterator.

fund.forEach((elA, i) => {
        if (elA.data) {
          const total = funders[i].data.reduce((acc, curr) => {
            acc += parseInt(curr.amount.replace(/\./g, ''))
            return acc
          }, 0)
          fund[i] = total ? {...elA, totalAmount: total} : elA;
        }
      });

Another alternative for the same code:

fund.forEach(elA => {
  if (elA.data) {
    const total = elA.data.reduce((acc, curr) => {
      return acc + parseInt(curr.amount.replace(/\./g, ''))
    }, 0)
    elA.totalAmount = total;
  }
});
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