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

如何用JavaScript将对象数组转换为指定分组结构?

JavaScript 对象数组按flag分组并格式化输出

原始数据与期望输出

原始变量与数组

const carCode = "F1.1";
const arr = [
    {
        "id": 169138,
        "name": "Volkswagen",
        "flag": "add"
    },
    {
        "id": 173212,
        "name": "Skoda",
        "flag": "add"
    },
    {
        "id": 175555,
        "name": "Mercedes",
        "flag": "delete"
    }
]

期望输出结构

{
    "F1.1": {
        "add": [
            {
                "id": 169138,
                "name": "volkswagen"
            },
            {
                "id": 173212,
                "name": "skoda"
            }
        ],
        "delete": [
            {
                "id": 175555,
                "name": "mercedes"
            }
        ]
    }
}

实现方案

方案一:使用Array.reduce()(简洁高效)

reduce是处理数组分组问题的常用方法,能直接遍历数组构建目标结构:

const result = arr.reduce((accumulator, currentItem) => {
    // 解构当前项属性,同时将name转为小写
    const { id, name, flag } = currentItem;
    const formattedItem = {
        id,
        name: name.toLowerCase()
    };

    // 初始化carCode对应的顶层对象(不存在则创建)
    if (!accumulator[carCode]) {
        accumulator[carCode] = {};
    }

    // 初始化当前flag对应的数组(不存在则创建空数组)
    if (!accumulator[carCode][flag]) {
        accumulator[carCode][flag] = [];
    }

    // 将格式化后的对象推入对应数组
    accumulator[carCode][flag].push(formattedItem);

    return accumulator;
}, {}); // 初始值为空对象

console.log(result);

方案二:普通for...of循环(新手友好,逻辑直观)

如果对reduce不熟悉,用普通循环的方式更易理解:

// 初始化结果对象
const result = {};
result[carCode] = {};

// 遍历原数组
for (const item of arr) {
    // 处理当前项,转换name为小写
    const newItem = {
        id: item.id,
        name: item.name.toLowerCase()
    };

    const flag = item.flag;
    // 如果当前flag对应的数组未初始化,先创建空数组
    if (!result[carCode][flag]) {
        result[carCode][flag] = [];
    }

    // 将处理后的对象加入对应数组
    result[carCode][flag].push(newItem);
}

console.log(result);

说明

两种方案都能实现需求,同时完成了name属性转为小写的处理。后续如果新增其他flag类型,代码也能自动适配分组,无需额外修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 20:12:32