很多时候,跟后端接口开发对接时,因为需求的关系,需要前端地区数据跟后端的数据要一一对应,所以一般来说前端应该是直接拿后端的地区数据,然后再来操作一下地区数据变成我们自己可以用的,有种情况,后台给到我们的是一堆一维数组,而我们需要的是多维数据,这时候就要操作数据了

直接上代码(使用的是vue):

下面的代码改成自己的就可以了,一般修改location_id, pid, childs, location_id为父级ID,pid为子级ID,当pid==location_id时,pid所在的数组就会放在父级下变成子数组

const city = require('./dlc_location.json');
created() {
  var json = city.RECORDS;
  //for (var i = 0; i < json.length; i++) {
  //  json[i].code = json[i].location_id;
  //}
  var CHINA_REGIONS = this.buildTree(json);
  console.log(CHINA_REGIONS);
}
methods: {
    buildTree(arr) {
      let temp = {};
      let tree = {};
      arr.forEach(item => {
        temp[item.location_id] = item;
      });

      let tempKeys = Object.keys(temp);
      tempKeys.forEach(key => {
        let item = temp[key];
        let _itemPId = item.pid;
        let parentItemByPid = temp[_itemPId];
        if (parentItemByPid) {
          if (!parentItemByPid.childs) {
            parentItemByPid.childs = [];
          }
          parentItemByPid.childs.push(item);
        } else {
          tree[item.location_id] = item;
        }
      });
      return Object.keys(tree).map(key => tree[key]);
    }
  },
Logo

前往低代码交流专区

更多推荐