数据扁平化、tree转换array转换tree

307 阅读1分钟
let arr = [
    { id: 1, name: '1', pid: 0 },
    { id: 2, name: '2', pid: 1 },
    { id: 3, name: '3', pid: 1 },
    { id: 4, name: '4', pid: 3 },
    { id: 5, name: '5', pid: 3 },
]
// 扁平化数据转换Tree
function arrayToTree (items) {
    let res = [];
    let getChildren = (res, pid) => {
        for (const i of items) {
            if (i.pid === pid) {
                const newItem = { ...i, children: [] };
                res.push(newItem);
                getChildren(newItem.children, newItem.id);
            }
        }
    };
    getChildren(res, 0);
    filterChildren(res);
    return res;
}
// 树形扁平化  树形转换数组
function treeToArray(tree) {
    let res = []
    for (const item of tree) {
      const { children, ...i } = item
      if (children && children.length) {
        res = res.concat(treeToArray(children))
      }
      res.push(i)
    }
    return res
  }
// 过滤空children
function filterChildren (data) {
    data.forEach(item => {
        if (item.children.length === 0) {
            delete item.children;
        } else {
            filterChildren(item.children);
        }
    });
}