扁平化

  1. // 树形扁平化
  2. export const treeDataToPlanishData = (list, parent, level = 0, clues = []) => { // eslint-disable-line
  3. return list.reduce((prev, {
  4. children = [],
  5. ...rest
  6. }) => {
  7. const parentKey = parent || '';
  8. const keyClues = clues.concat(rest.key);
  9. return prev.concat({ ...rest,
  10. parentKey,
  11. level,
  12. isLeaf: !!parentKey,
  13. keyClues,
  14. }, treeDataToPlanishData(children, rest.key, level + 1, keyClues));
  15. }, []);
  16. };

转树形

export const planishDataToTreeData = (data) => {
    const idMap = {};
    const jsonTree = [];
    data.forEach((v) => {
      idMap[v.key] = v;
    });
    data.forEach((v) => {
      const parent = idMap[v.parentKey];
      if (parent) {
        parent.children = parent.children || [];
        parent.children.push(v);
      } else {
        jsonTree.push(v);
      }
    });
  return jsonTree;
};