You need to enable JavaScript to run this app. 如何统计对象数组中相同的_id值并生成带messageCount字段的新数组
优惠活动
大模型
产品
解决方案
定价
更多

如何统计对象数组中相同的_id值并生成带messageCount字段的新数组

统计数组相同from._id出现次数的实现方案

实现思路

  • 首先创建一个临时映射结构(Map/普通对象均可),用来记录每个from._id对应的出现次数以及基础信息
  • 遍历原始数组,每匹配到一个相同的_id就给对应计数加1,首次出现的_id初始化计数为1
  • 最后把临时映射结构转换为目标格式的数组即可

JavaScript实现代码

// 原始数组
const originArr = [
  { from: {_id: "60dd7c7950d9e01088e438e0"} },
  { from: {_id: "60dd7c7950d9e01088e438e0"} },
  { from: {_id: "60dd7e19e6b26621247a35cd"} }
];

// 步骤1:用Map统计计数
const countMap = new Map();
originArr.forEach(item => {
  const id = item.from._id;
  if(countMap.has(id)) {
    countMap.get(id).messageCount += 1;
  } else {
    countMap.set(id, {
      from: {_id: id},
      messageCount: 1
    })
  }
});

// 步骤2:转换为目标数组
const resultArr = Array.from(countMap.values());
console.log(resultArr);

补充:reduce简化版本

也可以用Array.reduce方法一次性完成统计,代码更简洁:

const resultArr = Object.values(originArr.reduce((acc, cur) => {
  const id = cur.from._id;
  acc[id] = acc[id] 
    ? { ...acc[id], messageCount: acc[id].messageCount + 1 } 
    : { from: {_id: id}, messageCount: 1 };
  return acc;
}, {}));

输出验证

两种写法的输出都和预期结果完全一致:

[
  { from: { _id: '60dd7c7950d9e01088e438e0' }, messageCount: 2 },
  { from: { _id: '60dd7e19e6b26621247a35cd' }, messageCount: 1 }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 14:36:04