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

如何根据值嵌套JSON数据?按incident分组转换JSON结构

JSON数据分组转换解决方案

你可以通过临时分组映射的方式解决这个分组问题,核心是先把同属一个incident的项归到同一父节点下,再整理成目标结构。以下是具体的实现代码(以JavaScript为例):

实现代码

const input = [
    {
        "value": {
            "label": "MZ Algal bloom",
            "type": "case",
            "incident": { 
                "name": "Algal bloom"
            },
            "personName": "Lionel Carter"
        }
    },
    {
        "value": {
            "label": "BW Algal bloom",
            "type": "case",
            "incident": { 
                "name": "Algal bloom"
            },
            "personName": "Jerome Yost"
        }
    },
    {
        "value": {
            "label": "Detergent",
            "type": "case",
            "incident": null,
            "personName": "Jerald Legros"
        }
    }
];

// 用临时对象做分组映射,快速定位已存在的父节点
const groupMap = {};

input.forEach(item => {
    const { type, incident, personName, label } = item.value;
    
    if (incident) {
        const groupKey = incident.name;
        // 若分组不存在,先创建父节点结构
        if (!groupMap[groupKey]) {
            groupMap[groupKey] = {
                label: groupKey,
                children: []
            };
        }
        // 将当前项的personName和type作为子节点加入分组
        groupMap[groupKey].children.push({
            label: personName,
            type: type
        });
    } else {
        // incident为null时,直接生成独立节点
        groupMap[label] = {
            label: label,
            type: type
        };
    }
});

// 把映射中的值转为数组,得到最终结果
const output = Object.values(groupMap);
console.log(JSON.stringify(output, null, 2));

逻辑说明

  1. 分组映射:用groupMap存储每个父节点或独立节点,键为incident.name(有incident时)或原label(无incident时),确保同一incident的项会被归到同一个父节点下。
  2. 遍历处理:
    • 当incident不为null时,检查映射中是否已有对应父节点,没有则创建;然后将personName和type组成的子节点加入父节点的children数组。
    • 当incident为null时,直接将原label和type组成的节点存入映射。
  3. 结果转换:通过Object.values(groupMap)将映射中的节点提取为数组,就是你需要的目标结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 20:15:55