将后端返回的 List 转换成树结构

2018-04-16  本文已影响15人  赛亚人之神
this.$http.post('/api/staff/all').then(res => {

        if (200 === res.data.status) {
          let data = res.data.content;

          let map = {};

          // 将数组转换成 map
          data.forEach(item => map[item.organizationCode] = item);

          console.log(map);

          let output = [];

          data.forEach(item => {
            // 根据父 id 在 map 中查询是否存在,如果找到说明是该父元素的 child, 否则则是顶级元素
            let parent = map[item.origanizationParentCode];
            if (parent) {
              (parent.children || (parent.children = [])).push(item);
            } else {
              output.push(item);
            }
          });

          console.log(output, '过滤结果');

        }
      })
上一篇 下一篇

猜你喜欢

热点阅读