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

如何使用JavaScript将扁平结构JSON数组转换为嵌套聚合格式

JSON结构转换实现方案

实现思路

  • 以公共字段id作为分组标识,相同id的条目归为同一组
  • 每组提取公共字段,按照要求重命名映射为新的根层级字段
  • 遍历组内所有条目,将差异化字段按命名要求转换后推入channels数组
  • 最后将所有分组转换为数组形式返回即可

代码实现

function transformJson(originData) {
  // 用Map做分组,key为服务器id,value为转换后的根对象
  const groupMap = new Map();

  originData.forEach(item => {
    const serverId = item.id;
    // 当前id无分组时先创建分组
    if (!groupMap.has(serverId)) {
      groupMap.set(serverId, {
        id: serverId,
        serverIp: item.ip,
        serverPort: item.port,
        serverName: item.name,
        serverMacId: item.mac_id,
        channels: []
      })
    }
    // 向分组的channels数组添加转换后的通道数据
    groupMap.get(serverId).channels.push({
      id: item.cam_id,
      channelNo: item.dvr_analog_channel,
      name: item.cam_name
    })
  })

  // 将Map值转为数组,即为目标结构
  return Array.from(groupMap.values())
}

// 调用测试
const originData = [
    {
        "id": 76,
        "ip": "1.1.1.1",
        "port": 5000,
        "name": "Server",
        "mac_id": "asdasdaad121",
        "cam_id": 15363,
        "dvr_analog_channel": 33,
        "cam_name": "IP Channel 33"
    },
    {
        "id": 76,
        "ip": "1.1.1.1",
        "port": 5000,
        "name": "Server",
        "mac_id": "asdasdaad121",
        "cam_id": 15364,
        "dvr_analog_channel": 34,
        "cam_name": "IP Channel 34"
    },
    {
        "id": 76,
        "ip": "1.1.1.1",
        "port": 5000,
        "name": "Server",
        "mac_id": "asdasdaad121",
        "cam_id": 15365,
        "dvr_analog_channel": 35,
        "cam_name": "IP Channel 35"
    }
]
const result = transformJson(originData)
console.log(JSON.stringify(result, null, 2))

兼容说明

该实现自动支持多服务器场景,如果源数据中存在多个不同id的服务器,会自动分组为多个根对象,无需修改逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 07:06:08