关于数据处理(对复杂数据的映射处理)

要处理的数据结构:

// 要求: category_name为title,category_code为key,只需要title和key数据
 var arr = {
    "success": true,
    "message": null,
    "errorCode": null,
    "data": [{
      "category_code": "2261",
      "category_name": "涂料化工",
      "parent_code": "148",
      "hierarchy_level": "2",
      "children": [{
        "category_code": "2257",
        "category_name": "真石漆",
        "parent_code": "2261",
        "hierarchy_level": "3"
      }]
    }, {
      "category_code": "2260",
      "category_name": "装修石材",
      "parent_code": "148",
      "hierarchy_level": "2",
      "children": [{
        "category_code": "216",
        "category_name": "大理石",
        "parent_code": "2260",
        "hierarchy_level": "3"
      }]
    }]
  }

  function getMap(arr) {
    var data = []
    if (arr && arr.length > 0) {
      data = arr.map(item => {
        if (item.children && item.children.length > 0) {
          var res2 = getMap(item.children)
          return {
            title: item.category_name,
            key: item.category_code,
            children: res2
          }
        } else {
          return {
            title: item.category_name,
            key: item.category_code
          }
        }
      })
    }
   return data
  }
  console.log(getMap(dataArr))

你可能感兴趣的:(js)