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

如何对对象数组去重,将同grId对象的secTitle整合为secList?

JavaScript数组分组与属性转换实现

问题需求

将原始数组按grId分组去重,把同组的secTitle整合到secList数组中,同时将grId映射为id、grTitle映射为title。

原始数组

let arr1 = [
   {grId: 2, grTitle: "cls 1", secTitle: "sec A"},
   {grId: 2, grTitle: "cls 1", secTitle: "sec B"},
   {grId: 3, grTitle: "cls 2", secTitle: "sec A"},
   {grId: 3, grTitle: "cls 2", secTitle: "sec B"},
 ]

实现方案

使用Array.reduce()方法构建分组映射,再转换为目标数组:

const newArr = Object.values(arr1.reduce((acc, item) => {
  // 以grId作为分组唯一标识
  const key = item.grId;
  if (!acc[key]) {
    // 首次遇到该分组,初始化目标结构
    acc[key] = {
      id: item.grId,
      title: item.grTitle,
      secList: []
    };
  }
  // 将当前secTitle包装后加入分组的secList
  acc[key].secList.push({ secTitle: item.secTitle });
  return acc;
}, {}));

输出结果

执行后newArr将完全符合预期格式:

[
   {id: 2, title: "cls 1", secList: [{secTitle: "sec A"}, {secTitle: "sec B"}]},
   {id: 3, title: "cls 2", secList: [{secTitle: "sec A"}, {secTitle: "sec B"}]}
 ]

代码说明

  1. reduce遍历分组:遍历原始数组,用累加器acc存储分组后的中间对象,键为grId,值为目标结构的对象。
  2. 分组初始化:若累加器中无当前grId对应的键,则创建新的分组对象,设置id、title并初始化空的secList。
  3. 整合secTitle:将当前元素的secTitle包装为对象,推入对应分组的secList数组。
  4. 转换为最终数组:用Object.values()将累加器的对象值提取为数组,得到目标结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 19:10:31