我需要通過匹配物件屬性來求和值的幫助。例如,一個物件可能如下所示:
{
proc_nm: 'postgres-loader',
count: '290',
date_trunc: '2021-11-03T14:00:00.000Z'
}
我想對count具有匹配屬性的物件的值求和,例如 with NAMES('postgres-loader' etc)。
如何才能做到這一點?
uj5u.com熱心網友回復:
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);
uj5u.com熱心網友回復:
使用forEach是一種選擇。
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);
Array.prototype.forEach - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
如果您想按特定分組proc_nm并計算有多少物件具有相同的值,您可以使用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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/354372.html
標籤:javascript 数组 算法
上一篇:如何應用二分查找的主定理?
