I need help summing values by matching object properties. So for example, one object might look like this:
{
proc_nm: 'postgres-loader',
count: '290',
date_trunc: '2021-11-03T14:00:00.000Z'
}
I would like to sum the count
values of the objects that have a matching property, like with NAMES('postgres-loader' etc)
.
How can this be done?
CodePudding user response:
const names = ['postgres-loader', 'postgres-connector', 'postgres-reader'];
const variables = [
{
proc_nm: 'postgres-connector',
count: '290',
date_trunc: '2021-11-03T14:00:00.000Z'
},
{
proc_nm: 'postgres-loader',
count: '290',
date_trunc: '2021-11-03T14:00:00.000Z'
},
{
proc_nm: 'postgres-writer',
count: '290',
date_trunc: '2021-11-03T14:00:00.000Z'
}
];
let count = 0;
variables.forEach((variable) => {
if (names.includes(variable.proc_nm)) count ;
});
console.log(count);
CodePudding user response:
Using forEach
is an option.
const variables = [
{
proc_nm: 'postgres-connector',
count: '290',
date_trunc: '2021-11-03T14:00:00.000Z'
},
{
proc_nm: 'postgres-loader',
count: '290',
date_trunc: '2021-11-03T14:00:00.000Z'
},
{
proc_nm: 'postgres-writer',
count: '290',
date_trunc: '2021-11-03T14:00:00.000Z'
}
];
let count = 0;
variables.forEach(x => {
count = x.proc_nm === 'postgres-connector';
});
console.log(count);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Array.prototype.forEach - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
If you want to group by the specific proc_nm
and count how many objects have the same value you can use reduce
const variables = [
{
proc_nm: 'postgres-connector',
count: '290',
date_trunc: '2021-11-03T14:00:00.000Z'
},
{
proc_nm: 'postgres-loader',
count: '290',
date_trunc: '2021-11-03T14:00:00.000Z'
},
{
proc_nm: 'postgres-writer',
count: '290',
date_trunc: '2021-11-03T14:00:00.000Z'
},
{
proc_nm: 'postgres-writer',
count: '290',
date_trunc: '2021-11-03T14:00:00.000Z'
}
];
var result = [];
variables.reduce((res, value) => {
if (!res[value.proc_nm]) {
res[value.proc_nm] = { proc_nm: value.proc_nm, count: 0 };
result.push(res[value.proc_nm])
}
res[value.proc_nm].count = 1;
return res;
}, {});
console.log(result)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>