阅读 15

数组排序并转成树形结构

// 数组转成树形结构
export const toTree = function(arr) {
  let result = [];
  let data = JSON.parse(JSON.stringify(arr));
  if (!Array.isArray(data)) {
    return result;
  }
  data.sort(compare);     // 排序
  data.forEach(item => {
    delete item.children;
  });
  let map = {};
  data.forEach(item => {
    map[item.id] = item;
  });
  data.forEach(item => {
    let parent = map[item.pid];
    if (parent) {
      (parent.children || (parent.children = [])).push(item);
    } else {
      result.push(item);
    }
  });
  return result;
};

const compare = function(obj1, obj2) {
  let sort1 = obj1.sort;
  let sort2 = obj2.sort;
  if (sort1 < sort2) {
    return -1;
  } else if (sort1 > sort2) {
    return 1;
  } else {
    return 0;
  }
};
复制代码