Convert sequential storage to tree storage with recursion and loops (method comparison)

For some tree components, it is sometimes necessary to convert the data into a tree storage. Today, we will introduce two methods.

The first type: array loop, easy to understand

The second type: recursion, the code is simple, but it needs to be understood

First, let's define a variable

        const data = [
            { id: 56, parentId: 62, text: '文本1' },
            { id: 81, parentId: 80, text: '文本2' },
            { id: 74, parentId: null, text: '文本3' },
            { id: 76, parentId: 80, text: '文本4' },
            { id: 63, parentId: 62, text: '文本5' },
            { id: 80, parentId: 86, text: '文本6' },
            { id: 87, parentId: 86, text: '文本7' },
            { id: 62, parentId: 74, text: '文本8' },
            { id: 86, parentId: 74, text: '文本9' },
        ];

The first way: the way of array

Ideas:

1. Create a mapping table and add a corresponding index to each object so that the object can be quickly located in the array

Second, through the foreach loop to judge, and then increase the corresponding child elements

 Don't talk nonsense, let's go to the code

        // 建立映射关系
        const idMapping = data.reduce((acc, el, i) => {
            acc[el.id] = i;
            return acc;
        }, {});
        let root;
        data.forEach(el => {
            // 判断根节点
            if (el.parentId === null) {
                root = el;
                return;
            }
            // 用映射表找到父元素
            const parentEl = data[idMapping[el.parentId]];
            // 把当前元素添加到父元素的`children`数组中
            parentEl.children = [...(parentEl.children || []), el];

        });
        console.log(root);

renderings


The second: recursion (strongly recommended)

Idea: Encapsulate a function, use the method of pre-order traversal, call itself layer by layer, and perform traversal

        // 顺序表数据转换为树形存储
        function tranListToTreeData(depts, header) {
            const arr = []
            depts.forEach(item => {
                if (item.parentId === header) {
                    const children = tranListToTreeData(depts, item.id)
                    if (children.length) {
                        item.children = children
                    }
                    arr.push(item)
                }
            })
            return arr
        }
        console.log(tranListToTreeData(data, null));

renderings

 It's the same, isn't it? How many lines of code are written less?

Personal summary, the wrong place, I hope you can point it out, or a better way, leave a message in the comment area, and give everyone a knock

 

Guess you like

Origin blog.csdn.net/fightingLKP/article/details/126248590