如何用 js 递归输出树型

本文介绍了一种使用JavaScript实现的数据结构转换方法,通过递归函数和原型链扩展将一维数组转换为树状JSON对象。这种方法适用于需要快速构建复杂数据结构的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
</head>
<body>

    <script>

        var data = [
            { id: 1, title: 'a', pid: 0 },
            { id: 2, title: 'a1', pid: 1 },
            { id: 3, title: 'a11', pid: 2 },
            { id: 4, title: 'a12', pid: 2 },
            { id: 5, title: 'a2', pid: 1 },
            { id: 6, title: 'a21', pid: 5 }
        ];
        function fn(data, pid) {
            var result = [], temp;
            for (var i in data) {
                if (data[i].pid == pid) {
                    result.push(data[i]);
                    temp = fn(data, data[i].id);
                    if (temp.length > 0) {
                        data[i].children = temp;
                    }
                }
            }
            return result;
        }
        //console.log(fn(data, 0));


        Array.prototype.ToTreeJson = function (pid) {
            var result = [], temp;
            for (var i in this) {
                if (this[i].pid == pid) {
                    result.push(this[i]);
                    temp = fn(this, this[i].id);
                    if (temp.length > 0) {
                        this[i].children = temp;
                    }
                }
            }
            return result;
        }

        var p = data.ToTreeJson(0);
    </script>
</body>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值