数据转树形结构(递归实现)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app"></div>
    <script>
        var list = [
            { id:1, pid: 0, name: '总部'},
            { id:2, pid: 1, name: '北京分公司'},
            { id:3, pid: 1, name: '上海分公司'},
            { id:4, pid: 1, name: '广州分公司'},
            { id:5, pid: 1, name: '深圳3分公司'},
            { id:6, pid: 2, name: '朝阳经销商'},
            { id:7, pid: 2, name: '海淀经销商'},
            { id:8, pid: 3, name: '浦东经销商'},
        ]
        var div = document.getElementById('app')
        function tranListToTreeHtml (list, rootValue) {  // rootValue根值
            var html = '<ul>'
            list.forEach(item => {
                if (item.pid === rootValue) {
                var childHtml = tranListToTreeHtml(list, item.id)
                    html += `<li>${item.name}${childHtml}</li>`
                }
            });
            return html + '</ul>'
        }
        div.innerHTML = tranListToTreeHtml(list, 0)
    </script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/m0_49159526/article/details/112160977
今日推荐