js树形数据(数组)获取最深层级数

线上演示地址:https://wenyuming.github.io/maxFloor/ 

      接口返回的树形数据中不包含层级的时候,你需要获取最深层级数就需要自己写个函数获取,这篇博客就是为那些需获取最深层级数的人准备的。各路好汉来了就留个评论呗!

对你有帮助的话就帮我扫一下支付宝红包呗,不要的扫给我也可以,谢谢了各位,有啥需要可以在下方留言,多金大佬也可以打赏些小费。

js树形数据(数组)获取最深层级数_第1张图片

函数:

            getMaxFloor (treeData) {
                let floor = 0
                let v = this
                let max = 0
                function each (data, floor) {
                    data.forEach(e => {
                        e.floor = floor
                        if (floor > max) {
                            max = floor
                        }
                        if (e.children.length > 0) {
                            each(e.children, floor + 1)
                        }
                    })
                }
                each(treeData,1)
                return max
            }

示例数据:

 

[
	{
	  	"label": "广东省",
		"children": [
			{
				"label": "梅州市",
				"children": [
					{
						"label": "兴宁市",
						"children": [
							{
								"label": "黄槐镇",
								"children": [
									{
										"label": "西埔村",
										"children": []
									},
									{
										"label": "宝龙村",
										"children": []
									},
									{
										"label": "双下村",
										"children": []
									},
									{
										"label": "双头村",
										"children": []
									},
									{
										"label": "槐东村",
										"children": []
									}
								]
							}
						]
					}
				]
			}
		]
	},
	{"label": "一级2", "children": []},
	{"label": "一级3", "children": []}
]

gitHub小案例:https://github.com/wenyuming/maxFloor

你可能感兴趣的:(前端,数据,树形,js功能)