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

使用Groovy将JSON数组转换为含动态键的JSON对象

按动态section字段将JSON数组转换为分组JSON对象

需求说明

需要把包含section字段的JSON数组,转换为以section值(转为字符串)为键的JSON对象,每个键对应的数据包含total和data数组,其中data是移除了section字段的原数组元素。

JavaScript实现

const source = [
    {"a": 0, "section": 1.0},
    {"a": 1, "section": 1.0},
    {"a": 2, "section": 2.0},
    {"a": 3, "section": 2.0},
    {"a": 4, "section": 3.0}
];

const result = source.reduce((acc, item) => {
    // 把section的数值转为字符串键(比如1.0转成"1")
    const key = item.section.toString().split('.')[0];
    // 解构去除section字段
    const { section, ...rest } = item;
    
    // 初始化分组结构
    if (!acc[key]) {
        // 这里的total如果是业务自定义值,直接替换即可,比如key为"2"时设为5
        acc[key] = {
            total: 0,
            data: []
        };
    }
    
    acc[key].data.push(rest);
    // 若total是数据条数,直接取data的长度;如果是固定值,单独赋值
    acc[key].total = acc[key].data.length;
    
    return acc;
}, {});

console.log(JSON.stringify(result, null, 2));

Python实现

import json

source = [
    {"a": 0, "section": 1.0},
    {"a": 1, "section": 1.0},
    {"a": 2, "section": 2.0},
    {"a": 3, "section": 2.0},
    {"a": 4, "section": 3.0}
]

result = {}
for item in source:
    # 将section转为整数再转字符串,得到"1""2""3"这样的键
    key = str(int(item["section"]))
    # 移除section字段
    rest = {k: v for k, v in item.items() if k != "section"}
    
    if key not in result:
        # 自定义total值的话,这里根据key设置即可
        result[key] = {
            "total": 0,
            "data": []
        }
    
    result[key]["data"].append(rest)
    # 按数据条数更新total,自定义值替换为对应数值
    result[key]["total"] = len(result[key]["data"])

print(json.dumps(result, indent=2))

注意事项

如果示例中的total不是数据条数,而是特定业务值,只需要在初始化分组结构时,根据键名直接设置对应的total数值即可。比如在JS中:

if (!acc[key]) {
    let total;
    switch(key) {
        case "1": total = 1; break;
        case "2": total = 5; break;
        case "3": total = 4; break;
        default: total = 0;
    }
    acc[key] = { total, data: [] };
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 06:35:15