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

JavaScript中按BrandId分组数组对象并转换ActionCode为属性

JavaScript数组对象按BrandId分组并格式化统计数据

问题描述

现有如下JavaScript数组对象:

const ArrayExample = [
 { "BrandId": "5a52f163b56fbc1164c3f69a", "ActionCode": "MapNewInsert", "Total": 126, "TotalProduct": 127, "TotalBrand": 2 },
 { "BrandId": "5a52f163b56fbc1164c3f69a", "ActionCode": "MapNewUpdate", "Total": 0, "TotalProduct": 127, "TotalBrand": 2 },
 { "BrandId": "5a52f163b56fbc1164c3f69a", "ActionCode": "VerifyUpdate", "Total": 0, "TotalProduct": 127, "TotalBrand": 2 },
 { "BrandId": "5a52f163b56fbc1164c3f69a", "ActionCode": "VerifyDelete", "Total": 0, "TotalProduct": 127, "TotalBrand": 2 },
 { "BrandId": "5a52f163b56fbc1164c3f69a", "ActionCode": "Solved", "Total": 1, "TotalProduct": 127, "TotalBrand": 2 },
 { "BrandId": "5c10d62821cdfb2448a10a9c", "ActionCode": "MapNewInsert", "Total": 398, "TotalProduct": 398, "TotalBrand": 2 }
];

需要按BrandId分组,将每个项的ActionCode作为属性名,对应Total作为属性值;同时必须默认包含MapNewDelete、MapNewInsert、MapNewUpdate、Solved这几个属性,缺失的项值设为0。期望输出结构如下:

[
 { "BrandId": "5a52f163b56fbc1164c3f69a", "Statistics": { "MapNewDelete": 0, "MapNewInsert": 126, "MapNewUpdate": 0, "Solved": 1 } },
 { "BrandId": "5c10d62821cdfb2448a10a9c", "Statistics": { "MapNewDelete": 0, "MapNewInsert": 398, "MapNewUpdate": 0, "Solved": 0 } }
]

实现方案

这里用reduce来构建分组,结合预设的默认统计字段来确保输出结构符合要求,代码逻辑清晰且高效:

// 定义必须包含的默认统计字段及初始值
const defaultStats = {
  MapNewDelete: 0,
  MapNewInsert: 0,
  MapNewUpdate: 0,
  Solved: 0
};

const formattedResult = Object.values(
  ArrayExample.reduce((grouped, currentItem) => {
    // 初始化当前BrandId的分组结构(如果还不存在的话)
    if (!grouped[currentItem.BrandId]) {
      grouped[currentItem.BrandId] = {
        BrandId: currentItem.BrandId,
        // 复制默认统计对象,避免多个分组共享同一引用
        Statistics: { ...defaultStats }
      };
    }

    // 只更新默认字段范围内的ActionCode对应的Total值,忽略无关的ActionCode
    if (defaultStats.hasOwnProperty(currentItem.ActionCode)) {
      grouped[currentItem.BrandId].Statistics[currentItem.ActionCode] = currentItem.Total;
    }

    return grouped;
  }, {})
);

console.log(formattedResult);

代码逻辑说明

  1. 预设默认字段:defaultStats定义了所有必须出现在最终统计结果里的属性,确保即使原数组中没有对应ActionCode的项,也能保留默认值0。
  2. 分组构建:reduce遍历原数组,以BrandId作为键构建分组对象,每个分组初始化时都会带上完整的默认统计结构。
  3. 过滤并更新数据:只处理defaultStats中存在的ActionCode,自动忽略原数组里的无关字段(比如示例中的VerifyUpdate、VerifyDelete),避免污染统计结果。
  4. 转换为数组结构:最后用Object.values把分组对象的取值提取为数组,完全匹配期望的输出格式。

内容的提问来源于stack exchange,提问作者Minh Phu Pham

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 10:32:56