js递归json

2020-07-08 18:42 2023-12-04 14:25 标签:javascript,递归

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<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,
            name :"一级分类:1",
            pid :0,
        },
        {
            id:2,
            name :"二级分类:1",
            pid :1,
        },
        {
            id:3,
            name :"三级分类:3",
            pid :2,
        },
        {
            id:4,
            name :"一级分类:2",
            pid :0,
        },
        {
            id:7,
            name :"f级分类:2",
            pid :4,
        },
        {
            id:10,
            name :"f级分类:2",
            pid :7,
        },
        {
            id:9,
            name :"f级分类:2",
            pid :10,
        },
        {
            id:12,
            name :"f级分类:2",
            pid :9,
        },
        {
            id:15,
            name :"f级分类:2",
            pid :12,
        },
        {
            id:13,
            name :"f级分类:2",
            pid :15,
        },
    ]

    function toTree(data) {
        /* 删除 所有 children,以防止多次调用*/
        data.forEach(function (item) {
            delete item.children;
        });
        /* 将数据存储为 以 id 为 KEY 的 map 索引数据列*/
        var map = {};
        data.forEach(function (item) {
            map[item.id] = item;
        });
        var val = [];
        data.forEach(function (item) {
            /* 以当前遍历项,的pid,去map对象中找到索引的id*/
            var parent = map[item.pid];
            /* 如果找到索引,那么说明此项不在顶级当中,那么需要把此项添加到,他对应的父级中*/
            if (parent) {
                (parent.children || ( parent.children = [] )).push(item);
            } else {
                /*如果在map中没找到对应的索引ID,直接把当前的item添加到val结果集中,作为顶级*/
                val.push(item);
            }
        });
        return val;
    }
  console.log(toTree(data));
</script>
</body>
</html>


运行后结果如下

[{
	"id": 1,
	"name": "一级分类:1",
	"pid": 0,
	"children": [{
		"id": 2,
		"name": "二级分类:1",
		"pid": 1,
		"children": [{
			"id": 3,
			"name": "三级分类:3",
			"pid": 2
		}]
	}]
}, {
	"id": 4,
	"name": "一级分类:2",
	"pid": 0,
	"children": [{
		"id": 7,
		"name": "f级分类:2",
		"pid": 4,
		"children": [{
			"id": 10,
			"name": "f级分类:2",
			"pid": 7,
			"children": [{
				"id": 9,
				"name": "f级分类:2",
				"pid": 10,
				"children": [{
					"id": 12,
					"name": "f级分类:2",
					"pid": 9,
					"children": [{
						"id": 15,
						"name": "f级分类:2",
						"pid": 12,
						"children": [{
							"id": 13,
							"name": "f级分类:2",
							"pid": 15
						}]
					}]
				}]
			}]
		}]
	}]
}]


压缩解压