js递归树结构(根据子节点取父节点)

data: [{
	id: 1,
	label: '一级 1',
	children: [{
		id: 4,
		label: '二级 1-1',
		children: [{
			id: 9,
			label: '三级 1-1-1'
		}, {
			id: 10,
			label: '三级 1-1-2'
		}]
	}]
}, {
	id: 2,
	label: '一级 2',
	children: [{
		id: 5,
		label: '二级 2-1'
	}, {
		id: 6,
		label: '二级 2-2'
	}]
}, {
	id: 3,
	label: '一级 3',
	children: [{
		id: 7,
		label: '二级 3-1'
	}, {
		id: 8,
		label: '二级 3-2'
	}]
}],
getparentlist(code, tree) {
	let arr = [] //要返回的数组
	for (let i = 0; i < tree.length; i++) {
		let item = tree[i]
		arr = []
		arr.push(item.id) //保存当前节点id
		if (code == item.id) { //判断当前id是否是默认id
			return arr //是则退出循环、返回数据
		} else { //否则进入下面判断,判断当前节点是否有子节点数据
			if (item.children && item.children.length > 0) {
                //合并子节点返回的数据
				arr = arr.concat(this.getparentlist(code, item.children)) 
				if (arr.includes(code)) { //如果当前数据中已包含默认节点,则退出循环、返回数据
					return arr
				}
			}
		}
	}
},
 
test() {
	console.log(this.getparentlist(10, this.data))
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JavaScript中,我们可以通过遍历树结构来获某个父节点下的所有子节点。下面是一个使用递归方法来实现的示例代码: ```javascript // 定义树结构数据 var data = [ { id: 1, name: '节点1', children: [ { id: 2, name: '节点1-1', children: [] }, { id: 3, name: '节点1-2', children: [ { id: 4, name: '节点1-2-1', children: [] }, { id: 5, name: '节点1-2-2', children: [] } ] } ] }, { id: 6, name: '节点2', children: [] }, { id: 7, name: '节点3', children: [] } ]; // 定义函数来获指定父节点下的所有子节点 function getChildren(parentNode, result) { for (var i = 0; i < parentNode.children.length; i++) { var childNode = parentNode.children[i]; result.push(childNode); // 将子节点添加到结果数组中 if (childNode.children.length > 0) { getChildren(childNode, result); // 递归调用获子节点子节点 } } } // 调用函数来获指定父节点下的所有子节点 var parentId = 1; // 指定父节点的id var parent = data.find(node => node.id === parentId); // 找到指定的父节点 var children = []; // 用于存储子节点的结果数组 getChildren(parent, children); console.log(children); // 输出结果:[{ id: 2, name: '节点1-1', children: [] }, { id: 3, name: '节点1-2', children: [...] }, { id: 4, name: '节点1-2-1', children: [] }, { id: 5, name: '节点1-2-2', children: [] }] ``` 以上代码中,我们首先定义了一个包含树结构的数据数组。然后,我们通过定义一个`getChildren`函数,使用递归的方式遍历树结构,从指定的父节点开始获所有子节点。最后,我们调用这个函数来获指定父节点下的所有子节点,并将结果存储在一个数组中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值