根据某个值,查找最顶端的值

现有数据结构

let list = [
	{
		key: '/a',
		children: [
			{
				key: 'b',
				chilren: [
					{
						key: '/c',
						children: [
							{
								key: '/d',
							}
						]
					}
				]
			}
		]
	},
	{
		key: '/a1',
		children: [
			{
				key: 'b1',
				chilren: [
					{
						key: '/c1',
						children: [
							{
								key: '/d1',
							}
						]
					}
				]
			}
		]
	}
]

要求根据/c1 找到最顶端的key。
方法如下:

const findTopKey = (list, targetKey) => {
  for (const root of list) {
    if (findInTree(root, targetKey)) {
      return root.key;
    }
  }
  return null;
}
const findInTree = (node, targetKey) => {
  if (node.key === targetKey) {
    return true;
  }
  if (node.children) {
    for (const child of node.children) {
      if (findInTree(child, targetKey)) {
        return true;
      }
    }
  }
  return false;
}
const parentKey =  findTopKey(items.value, activeMenu?.value[0]);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值