Diego Braga
Diego Braga

Reputation: 221

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
}

Upvotes: 0

Views: 95

Answers (3)

Andy
Andy

Reputation: 63514

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 });

Upvotes: 1

Devesh
Devesh

Reputation: 613

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);

Upvotes: 1

moonstar-x
moonstar-x

Reputation: 1148

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)
};

Upvotes: 4

Related Questions