js将数组中具有父子关系的元素转换为树形结构数据

1.代码如下:

const data = [{
     
            id: 1,
            name: '1',
        }, {
     
            id: 2,
            name: '1-1',
            parentId: 1
        }, {
     
            id: 3,
            name: '1-1-1',
            parentId: 2
        }, {
     
            id: 4,
            name: '1-2',
            parentId: 1
        }, {
     
            id: 5,
            name: '1-2-2',
            parentId: 4
        }, {
     
            id: 6,
            name: '1-1-1-1',
            parentId: 3
        }, {
     
            id: 7,
            name: '2',
        }]

        // 4.把父子关系的数组转换为树形结构
        function translateDataToTree(data) {
     
            const treeData = [];
            for (let i = 0; i < data.length; i++) {
     
                let ele = data[i];
                if (!ele.parentId) {
     
                    treeData.push(ele); // ele为根节点时,push到treeData中
                    continue;
                }
                translateChildren(treeData, ele);
            }
            function translateChildren(arr, ele) {
     
                arr.forEach(item => {
     
                    if (ele.parentId === item.id) {
     
                        if (!item.children) item.children = [];
                        item.children.push(ele);
                    }
                    if (item.children) {
     
                        translateChildren(item.children, ele); // 递归遍历
                    }
                })
            }
            return treeData;
        }

        const tree = translateDataToTree(data);
        console.log(tree);

你可能感兴趣的:(js基础)