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

JavaScript实现:将相同键值的对象合并到子数组中

实现思路与代码示例

步骤拆解

  • 先按type对原数组元素进行归类,统计每个type对应的所有元素
  • 根据每个type下的元素数量处理:元素数量大于1的,包装成带title和sub_items的结构;数量为1的直接保留原对象
  • 最后整理成目标格式的数组

代码实现

const originalData = [
  { type: "1", name: "Anthony" },
  { type: "1", name: "Linus" },
  { type: "2", name: "Sebastin" },
];

// 按type归类所有元素
const typeGroup = originalData.reduce((group, item) => {
  const key = item.type;
  if (!group[key]) {
    group[key] = [];
  }
  group[key].push(item);
  return group;
}, {});

// 转换为目标结构
const result = Object.entries(typeGroup).map(([type, items]) => {
  return items.length > 1 
    ? { title: type, sub_items: items } 
    : items[0];
});

console.log(result);

代码说明

  • 用reduce方法遍历原数组,把同type的元素归集到同一个数组中,生成type为键、对应元素数组为值的映射对象
  • 遍历映射对象的键值对,判断每个type下的元素数量:数量多于1时生成包含title和sub_items的分组对象;仅单个元素时直接返回原对象
  • 最终得到的result数组就是你需要的格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 04:20:32