JS将一个不止深度的对象转换成树结构

JS将一个不止深度的对象转换成树结构

示例数据
{
  "CODE": 200,
  "MSG": "SUCCESS",
  "ENT_INFO": {
    "BREAKLAW": [],
    "ORGDETAIL": {},
    "YEARREPORTBASIC": [
      {
        "ANCHEYEAR": "2013",
        "POSTALCODE": "300457",
        "ANCHEDATE": "2014-11-26",
        "BUSST": "开业",
        "EMAIL": "[email protected]",
        "WOMEMPNUM": "",
        "ANCHEID": "f07b130d19d830db52cae8807dbacc77",
        "ADDR": "天津经济技术开发区黄海路118号",
        "HOLDINGSMSG_CN": "",
        "REGNO": "120191000002366",
        "CREDITNO": "911201166630834097",
        "MAINBUSIACT": "",
        "ENTNAME": "天津乖乖投资控股集团有限公司",
        "TEL": "66252677",
        "EMPNUM": "2"
      }
    ],
    "METADATA": { "SOURCE": "1" },
    "MORTGAGEALT": []
  }
}

转换方法
function convertJSON(jsonObj) {
  let result = [];
  
  for (let key in jsonObj) {
    let param = {
      paramKey: key,
      paramValue: jsonObj[key],
      paramType: Array.isArray(jsonObj[key]) ? 12 : 13,
      children: []
    };
    
    if (typeof jsonObj[key] === 'object' && !Array.isArray(jsonObj[key])) {
      param.children = convertJSON(jsonObj[key]);
    } else if (Array.isArray(jsonObj[key])) {
      for (let i = 0; i < jsonObj[key].length; i++) {
        let arrayParam = {
          paramKey: "",
          paramValue: "",
          paramType: 13,
          children: convertJSON(jsonObj[key][i])
        };
        param.children.push(arrayParam);
      }
    }
    
    result.push(param);
  }
  
  return result;
}

转换结果
JS将一个不止深度的对象转换成树结构_第1张图片

你可能感兴趣的:(javascript,开发语言,ecmascript)