You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据匹配的对象属性值对对应count字段进行求和计算

按属性匹配求和的实现方案

原生JavaScript实现(处理对象数组场景)

你可以通过数组的reduce方法结合匹配判断实现需求,完整代码示例如下:

// 定义需要匹配的proc_nm白名单
const matchNames = ['postgres-loader', '你的其他进程名1', '你的其他进程名2']
// 原始数据数组
const originData = [
  { proc_nm: 'postgres-loader', count: '290', date_trunc: '2021-11-03T14:00:00.000Z' },
  { proc_nm: 'mysql-loader', count: '120', date_trunc: '2021-11-03T14:00:00.000Z' },
  { proc_nm: 'postgres-loader', count: '310', date_trunc: '2021-11-03T15:00:00.000Z' }
]

// 求和计算
const sumCount = originData.reduce((total, current) => {
  // 仅累加匹配白名单的项
  if (matchNames.includes(current.proc_nm)) {
    // 注意count为字符串类型,需转换为数值再计算
    total += Number(current.count)
  }
  return total
}, 0)

console.log(sumCount) // 上述示例输出结果为600
  • 兼容旧浏览器可将matchNames.includes(current.proc_nm)替换为matchNames.indexOf(current.proc_nm) !== -1
  • 若存在count为非数字的异常数据,可增加容错处理:total += isNaN(Number(current.count)) ? 0 : Number(current.count)

SQL场景实现(数据表聚合统计场景)

如果数据存储在关系型数据库中,可直接通过SQL聚合语句实现,假设表名为proc_runtime_stats,对应字段和示例对象属性一致:

-- MySQL语法示例
SELECT SUM(CAST(count AS UNSIGNED)) AS total_count
FROM proc_runtime_stats
WHERE proc_nm IN ('postgres-loader', '你的其他进程名1', '你的其他进程名2');

不同数据库的类型转换语法略有差异,PostgreSQL可写为count::INTEGER,Oracle可写为TO_NUMBER(count),根据实际使用的数据库调整即可

内容的提问来源于stack exchange,提问作者JJJ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 11:18:00