树形(tree)结构构建方法浅析

315 阅读1分钟
  • 非递归扁平化处理方案 原始数据数据结构:
interface Item {
    id: number;
    parentId: number | null;
    ...
}

构建后数据结构:

interface handledItem {
    id: number;
    parentId: number | null;
    ...
    children: handledItem[] || [];
}
function formatDataTree(data: any) {

  return data.filter((p: { id: any; children: any; pid: number }) => {

    const childArr = _data.filter((c: { pid: any }) => c.pid === p.id);

    childArr.length && (p.children = childArr);

    return p.pid === null;

  });

}
  • 无限极子数据递归处理方案 原理:1、顶级与子集数据分开;2、数据递归处理;
function formatDataTree (data) {

    const parentList = data.filter(p => p.pid === null);        // 此处假设顶级数据字段id值为null

    const childList = data.filter(c => c.pid !== null);

    dataToTree(parentList, childList);

    return parentList;


    function dataToTree (parentList, childList) {

        parentList.map(p => {

            childList.map((c, i) => {

                if (c.pid === p.id) {

                    const _childList = JSON.parse(JSON.stringify(childList));

                    _childList.splice(i, 1);

                    dataToTree([c], _childList);

                    if (p.children) {

                        p.children.push(c);

                    }

                    else {

                        p.children = [c];

                    }

                }

            })

        })

    }

}