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
}
CodePudding user response:
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)
};
CodePudding user response:
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);
CodePudding user response:
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 });