mario-mui / blog

0 stars 0 forks source link

把树结构转成数组,保持顺序。例如把多级左导航列表形式展示 #5

Open mario-mui opened 2 years ago

mario-mui commented 2 years ago
import {reverse} from 'lodash'

treeToArray(tree) {
    const stack = reverse(tree);
    const array = [];
    while (stack.length !== 0) {
      const node = stack.pop();
      node.level = node.level || 0;
      if (node.children?.length) {
        reverse(node.children).forEach(i => {
          stack.push({ ...i, level: node.level + 1 });
        });
      }
      array.push(node);
    }
    return array;
  }