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

85
Views
get total sum every count inside array of objects javascript

It should be a simple task but I'm having a little bit of trouble
doing it.

I have the following object:

{
  "chatRoom": [
    {
      "_count": {
        "publicMessages": 10
      }
    },
    {
      "_count": {
        "publicMessages": 10
      }
    },
    {
      "_count": {
        "publicMessages": 10
      }
    }
  ],
}

I would like to get the total sum of every value
inside "publicMessages"
The desidered output:

{
  "totalMessages": 30
}
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You can use the Array.reduce() function. If that object is inside a variable named obj, you can achieve this by using:

const result = {
  totalMessages: obj.chatRoom.reduce((acc, cur) => acc + cur._count.publicMessages, 0)
};
about 4 years ago · Juan Pablo Isaza Report

0

If you want something a little more verbose and understandable than reduce, a simple for/of loop might help you.

const data={chatRoom:[{_count:{publicMessages:10}},{_count:{publicMessages:10}},{_count:{publicMessages:10}}]};

// Initialise the total
let totalMessages = 0;

// Loop over the chatRoom array of objects
// and add the publicMessages value to the total
for (const obj of data.chatRoom) {
  totalMessages += obj._count.publicMessages;
}

// Log the total
console.log({ totalMessages });

about 4 years ago · Juan Pablo Isaza Report

0

Array.reduce() is the solution, you can run it like this:

const obj={chatRoom:[{_count:{publicMessages:10}},{_count:{publicMessages:10}},{_count:{publicMessages:10}}]};

let sum = obj.chatRoom.reduce( (acc, curr)=>{ return acc+=curr._count.publicMessages??0},0);

console.log(sum);

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!