JS实现根据对象之间的id以及pid构建目录树

1.遍历得到顶层节点

        var resultObj = []	
        function fn(jsonData) {
				//取得顶级的数据
				var baseNode = jsonData.filter(function(element) {
					return element.pid === 0
				})
				resultObj.push(...baseNode)
				getChildren(resultObj, jsonData)
			}

2.递归取得顶层节点的子节点

			function getChildren(nodeList, jsonData) {
				nodeList.forEach(function(elemet, index) {
					elemet.childrenNode = jsonData.filter(function(item, indexI) {
						return item.pid === elemet.id
					})
					if(elemet.childrenNode.length > 0) {
						getChildren(elemet.childrenNode, jsonData)
					}
				})
			}

猜你喜欢

转载自blog.csdn.net/weixin_42011096/article/details/81097376