前端转化树结构1

前端转化树结构1 后端关系型数据库

var data = [{
  "province": "浙江",
  "city": "杭州",
  "name": "西湖"
}, {
  "province": "四川",
  "city": "成都",
  "name": "锦里"
}, {
  "province": "四川",
  "city": "成都",
  "name": "方所"
}, {
  "province": "四川",
  "city": "阿坝",
  "name": "九寨沟"
}] 

转化为

var data = [{
  "value": "浙江",
  "children": [{
    "value": "杭州",
    "children": [{
      "value": "西湖"
    }]
  }]
}, {
  "value": "四川",
  "children": [{
    "value": "成都",
    "children": [{
      "value": "锦里"
    }, {
      "value": "方所"
    }]
  }, {
    "value": "阿坝",
    "children": [{
      "value": "九寨沟"
    }]
  }]
}]

直接上转化函数:

transObject(tableData, keys) {
      let hashTable = {},
        res = [];
      for (let i = 0; i < tableData.length; i++) {
        let arr = res,
          cur = hashTable;
        for (let j = 0; j < keys.length; j++) {
          let key = keys[j],
            filed = tableData[i][key];
          if (!cur[filed]) {
            let pusher = {
                value: filed,
              },
              tmp;
            if (j !== keys.length - 1) {
              tmp = [];
              pusher.children = tmp;
            }
            cur[filed] = { $$pos: arr.push(pusher) - 1 };
            cur = cur[filed];
            arr = tmp;
          } else {
            cur = cur[filed];
            arr = arr[cur.$$pos].children;
          }
        }
      }
      return res;
    },

使用:

this.transObject(list, ["province", "city", "name", "title"])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值