Home  >  Article  >  Web Front-end  >  JavaScript code example to implement infinite recursion tree

JavaScript code example to implement infinite recursion tree

不言
不言forward
2019-03-29 09:37:372601browse

The content of this article is about code examples for implementing infinite recursion trees in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Demand: Recently I encountered a requirement. I was usually used by the backend to directly return the tree structure to the front end. The front end is very sensitive to this nested type of data (such as the cascade of regions or the tree structure of menus). ) saves a layer of processing. After changing the background development, the flattened array data was returned to the front end to process the following data. Suddenly I felt a little panic...

const data = [
    {
        "area_id": 5,
        "name": "广东省",
        "parent_id": 0,
    },  
    {
        "area_id": 6,
        "name": "广州市",
        "parent_id": 5,
    },
    {
        "area_id": 7,
        "name": "深圳市",
        "parent_id": 5,
    },
    {
        "area_id": 4,
        "name": "北京市",
        "parent_id": 3,
    },
    {
        "area_id": 3,
        "name": "北京",
        "parent_id": 0,
    },
    {
        "area_id": 2,
        "name": "测试子地区",
        "parent_id": 1,
    },
    {
        "area_id": 1,
        "name": "测试地区",
        "parent_id": 0,
    }
]

emmm, I changed my mind and thought about it, it was just right to exercise, roll up my sleeves and do it, and then I summarized the following two organizing methods~

Method 1 - Recursion

In such a scenario that is so suitable for recursion, how can the role of recursion be omitted? The first method is recursion! Presenting the treasure of recursion~

function toTreeData(data,pid){
 
    function tree(id) {
        let arr = []
        data.filter(item => {
            return item.parent_id === id;
        }).forEach(item => {
            arr.push({
                area_id: item.area_id,
                label: item.name,
                children: tree(item.area_id)
            })
        })
        return arr
    }
    return tree(pid)  // 第一级节点的父id,是null或者0,视情况传入
}

Well, pose properly, execute it in the console

JavaScript code example to implement infinite recursion tree

Oh, not bad~The little brother in the background no longer has to worry What data needs to be returned to me? However, this method has a disadvantage. In the data structure I need when using the component, if there is no data in the child, [] is returned. Well, there is a problem, but it can still be optimized. Will I be able to provide the optimized code so easily? You are already a mature programmer and need to learn to optimize the code yourself! ! !

Method 2 - Object

The object has always been the existence of the Heaven-Eternal Dragon-Slaying Sword in my eyes, and understanding the secret is like having a martial arts secret book close to me. Of course, not using it properly is equivalent to a pile of scrap metal, and may even lead to some unpredictable results.

function setTreeData(arr) {
    //  删除所有 children,以防止多次调用
    arr.forEach(function (item) {
            delete item.children;
    });
    let map = {}; // 构建map
    arr.forEach(i => {
        map[i.area_id] = i; // 构建以area_id为键 当前数据为值
    });

    let treeData = [];
    arr.forEach(child => {
        const mapItem = map[child.parent_id]; // 判断当前数据的parent_id是否存在map中

        if (mapItem) { // 存在则表示当前数据不是最顶层数据
        
            // 注意: 这里的map中的数据是引用了arr的它的指向还是arr,当mapItem改变时arr也会改变,踩坑点
            (mapItem.children || ( mapItem.children = [] )).push(child); // 这里判断mapItem中是否存在children, 存在则插入当前数据, 不存在则赋值children为[]然后再插入当前数据
        } else { // 不存在则是组顶层数据
            treeData.push(child);
        }
    });

    return treeData;
};

console.log(setTreeData(data)); // 输出整理后的数据

As a result, I will not execute it, which is similar to the recursive result. I prefer this approach to recursion. However, this method is easy to make mistakes, that is, it will change the original data. I have been stuck here for a long time, so I initialized it by deleting children. Have you remembered? If not, repeat yourself three times! ! !

Summary

The above briefly introduces two methods of converting flat data into recursive trees. Have you learned it? If not, go back and code! At present, when I encounter the need to organize data into a tree structure, it is mainly in the tree structure of the menu bar or classification. Of course, there are also subordinate structures such as provinces and cities.

This article has ended here. For more other exciting content, you can pay attention to the JavaScript Tutorial Video column of the PHP Chinese website! ! !

The above is the detailed content of JavaScript code example to implement infinite recursion tree. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete