Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

99
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!