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

后端返回的运营商网络数组按zone、country、operator层级重组需求

扁平数组转嵌套层级结构方案

实现逻辑

  • 借助对象的键唯一性做去重判断,相比数组遍历查重效率更高,全流程仅需遍历原始数组1次
  • 每一层级初始化时可直接补充你需要的自定义字段,可按需修改默认值
  • 最终将顶层存储的zone集合转换为数组即可得到目标结构

代码示例(JavaScript 版本)

function formatNestedData(rawData) {
  // 存储顶层zone映射,键为zone名称,值为zone对象
  const zoneMap = {}

  rawData.forEach(item => {
    const { zone, country, operator_alias, network_code } = item
    // 1. 处理zone层级
    if (!zoneMap[zone]) {
      zoneMap[zone] = {
        zone: zone,
        Zone_Price: '0', // 可自定义默认值
        Active: 'true',
        countries: []
      }
    }
    const currentZone = zoneMap[zone]

    // 2. 处理country层级
    let currentCountry = currentZone.countries.find(c => c.country_name === country)
    if (!currentCountry) {
      currentCountry = {
        country_name: country,
        active: 'true', // 可自定义默认值
        operators: []
      }
      currentZone.countries.push(currentCountry)
    }

    // 3. 处理运营商层级
    let currentOperator = currentCountry.operators.find(o => o.operator_name === operator_alias)
    if (!currentOperator) {
      currentOperator = {
        operator_name: operator_alias,
        active: 'true', // 可自定义默认值
        operator_code: []
      }
      currentCountry.operators.push(currentOperator)
    }

    // 4. 处理network_code层级
    let currentCode = currentOperator.operator_code.find(c => c.operator_code === network_code)
    if (!currentCode) {
      currentCode = {
        operator_code: network_code,
        active: 'true' // 可自定义默认值
      }
      currentOperator.operator_code.push(currentCode)
    }
  })

  // 把zone映射对象转为数组返回
  return Object.values(zoneMap)
}

调用示例

你直接把后端返回的原始数组传入函数即可得到符合要求的嵌套结构:

const rawData = [
  {
    "_id": "615d40a21503e000147d4e97",
    "zone": "A",
    "country": "India", 
    "operator_alias": "Idea",
    "network_code": "2590"
  }
]
const result = formatNestedData(rawData)
console.log(result)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 14:18:03