You need to enable JavaScript to run this app. JavaScript对象数组如何按title键合并重复项并适配边界场景
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript对象数组如何按title键合并重复项并适配边界场景

同title对象属性合并实现方案

核心逻辑

使用Map作为唯一title的缓存容器,遍历原数组时按title做属性合并,最后输出Map存储的所有合并项即可,完全适配要求的边界规则。

完整实现代码

function mergeItemsByTitle(sourceArr) {
  // 单元素/空数组直接返回,无需额外处理
  if (sourceArr.length <= 1) return sourceArr;

  const titleCache = new Map();
  for (const item of sourceArr) {
    const targetTitle = item.title;
    if (titleCache.has(targetTitle)) {
      // 已有同title项,将当前项的属性合并到缓存对象中
      Object.assign(titleCache.get(targetTitle), item);
    } else {
      // 无同title项,存入浅拷贝对象,避免修改原数组的对象引用
      titleCache.set(targetTitle, { ...item });
    }
  }
  // 转换为普通数组返回
  return Array.from(titleCache.values());
}

规则适配说明

  • 单元素场景:直接命中sourceArr.length <= 1的判断逻辑,原样返回输入数组
  • 无重复title场景:每个title对应Map中独立的缓存项,无合并操作,完全保留原有对象结构
  • 重复title场景:自动将同title对象的所有独立属性合并到同一对象中,不会丢失任意属性;若存在同title下的重复非title属性,默认以后遍历到的属性值为准,符合常规合并预期

注:你给出的期望输出中{"title": "book3": isInFrench: true}为语法书写笔误,实际运行输出的是{"title": "book3", "isInFrench": true},与预期逻辑完全一致。

测试验证

// 输入测试数组
const testInput = [{"title": "book1", isInEnglish: true}, {"title": "book1", isInFrench: true}, {"title": "book2", isInEnglish: true}, {"title": "book2", isInItalian: true}, {"title": "book1", isInItalian: true}, {"title": "book3", isInFrench: true}];

// 调用合并函数
const mergedResult = mergeItemsByTitle(testInput);
console.log(mergedResult);
/* 输出结果:
[
  {"title": "book1", isInEnglish: true, isInFrench: true, isInItalian: true},
  {"title": "book2", isInEnglish: true, isInItalian: true},
  {"title": "book3", isInFrench: true}
]
*/

内容的提问来源于stack exchange,提问作者C.J

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.20 06:15:08