如何根据值嵌套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));
逻辑说明
- 分组映射:用
groupMap存储每个父节点或独立节点,键为incident.name(有incident时)或原label(无incident时),确保同一incident的项会被归到同一个父节点下。 - 遍历处理:
- 当
incident不为null时,检查映射中是否已有对应父节点,没有则创建;然后将personName和type组成的子节点加入父节点的children数组。 - 当
incident为null时,直接将原label和type组成的节点存入映射。
- 当
- 结果转换:通过
Object.values(groupMap)将映射中的节点提取为数组,就是你需要的目标结构。
内容的提问来源于stack exchange,提问作者baradhili
相关产品推荐
相关产品推荐

