递归与遍历修改数据类型

112 阅读1分钟

期望为:

image.png

const address = [
        {
          'name': '北京',
          'city': [{
            'name': '北京',
            'area': ['东城区', '西城区', '崇文区', '宣武区', '朝阳区', 
            '丰台区', '石景山区', '海淀区', '门头沟区', '房山区', '通州区', 
            '顺义区', '昌平区', '大兴区', '平谷区', '怀柔区', '密云县', '延庆县']
          }]
        },
        {
          'name': '河北',
          'city': [
            {
              'name': '石家庄',
              'area': ['长安区', '桥东区', '桥西区', '新华区', '郊  区',
              '井陉矿区', '井陉县', '正定县', '栾城县', '行唐县', '灵寿县',
              '高邑县', '深泽县', '赞皇县', '无极县', '平山县', '元氏县', 
              '赵  县', '辛集市', '藁', '晋州市', '新乐市', '鹿泉市']
            },
            {
              'name': '唐山',
              'area': ['路南区', '路北区', '古冶区', '开平区', '新  区', 
              '丰润县', '滦  县', '滦南县', '乐亭县', '迁西县', '玉田县',
              '唐海县', '遵化市', '丰南市', '迁安市']
            },
          ]
        }
        ]
        
  //递归
  formatData(o) {
    let temp = {}
    for (let key in o) {
      if (o[key].constructor == Array) {
        temp.children = []
        o[key].forEach(el => {
          if (typeof el == 'string'){
            const area = {}
            area.value = el
            area.lable = el
            temp.children.push(area)
          }else{
            // temp.children.push(this.formatData(o[key]))
            temp.children = this.formatData(o[key])
          }
        })
      } else if(o[key].constructor == Object){
        temp[key] = this.formatData(o[key])
      } else {
        temp.value = o[key]
        temp.lable = o[key]
      }
    }

    return temp
  }
  
  //普通遍历
    const options = []
    address.map(el => {
      const obj= {}
      obj.value = el.name
      obj.lable = el.name
      obj.children = []
      el.city.map(en => {
         const cityObj = {}
         cityObj.value = en.name
         cityObj.lable = en.name
         cityObj.children = []
         en.area.map(e => {
            const newArea = {}
            newArea.value = e
            newArea.lable = e
            cityObj.children.push(newArea)
      })
      obj.children.push(cityObj)
    })
      options.push(obj)
   })