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

JavaScript如何按双字段对数组对象分组并聚合其余属性

实现方案

基础实现(适配当前需求场景)

直接针对你给出的字段结构编写,逻辑简单易读:

function groupCategory(arr) {
  const tempMap = {};
  arr.forEach(item => {
    // 拼接两个分组字段作为唯一key,避免不同分组重名冲突
    const key = `${item.categoryCode}|${item.categoryName}`;
    if (!tempMap[key]) {
      tempMap[key] = {
        categoryCode: item.categoryCode,
        categoryName: item.categoryName,
        cat_type: []
      };
    }
    tempMap[key].cat_type.push(item.cat_type);
  })
  // 将映射对象转为数组即为最终结果
  return Object.values(tempMap);
}

// 调用示例
const originData = [/* 你的原始数组 */];
const result = groupCategory(originData);

通用实现(支持自定义扩展)

如果后续需要更换分组字段、或者除分组字段外有多个需要聚合的字段,可以用这个通用版本:

/**
 * 按指定字段分组聚合数组
 * @param {Array} arr 原始数组
 * @param {Array} groupFields 需要作为分组依据的字段名数组
 * @returns 分组聚合后的数组
 */
function groupByFields(arr, groupFields = ['categoryCode', 'categoryName']) {
  const tempMap = {};
  arr.forEach(item => {
    // 生成分组唯一标识
    const groupKey = groupFields.map(field => item[field]).join('|');
    if (!tempMap[groupKey]) {
      // 初始化分组项,先赋值分组字段
      const groupItem = {};
      groupFields.forEach(field => groupItem[field] = item[field]);
      // 其余字段初始化为空数组
      Object.keys(item).forEach(key => {
        if (!groupFields.includes(key)) groupItem[key] = [];
      })
      tempMap[groupKey] = groupItem;
    }
    // 聚合非分组字段的值
    Object.keys(item).forEach(key => {
      if (!groupFields.includes(key)) tempMap[groupKey][key].push(item[key]);
    })
  })
  return Object.values(tempMap);
}

注:如果你的原始数据中A、B是字符串常量,记得在定义原始数组时给值加上引号,不影响上述逻辑执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 23:48:02