联想查询,数组中id和label,相互查询

const treeData = [
  {
    id: 1,
    label: 'a',
    children: [
      {
        id: 11,
        label: 'aa',
        children: [
          {
            id: 111,
            label: 'aaa',
            children: [
              {
                id: 1111,
                label: 'aaaa',
                children: [],
              }
            ]
          }
        ]
      },
      {
        id: 12,
        label: 'ab',
        children: [
          {
            id: 121,
            label: 'aba',
            children: [
              {
                id: 1211,
                label: 'abaa',
                children: [],
              }
            ]
          }
        ]
      },
    ]
  },
  {
    id: 2,
    label: 'b',
    children: [
      {
        id: 21,
        label: 'ba',
        children: [
          {
            id: 211,
            label: 'baa',
            children: [
              {
                id: 2111,
                label: 'baaa',
                children: [],
              }
            ]
          }
        ]
      }
    ]
  }
];

代码逻辑:

function findLabelsByIds(tree, ids) {
  const labels = [];
  
  function findNode(nodes, targetId) {
    for (const node of nodes) {
      if (node.id === targetId) {
        return node;
      }
      if (node.children && node.children.length) {
        const found = findNode(node.children, targetId);
        if (found) return found;
      }
    }
    return null;
  }

  for (const id of ids) {
    const node = findNode(tree, id);
    if (node) {
      labels.push(node.label);
    } else {
      labels.push(null); // 如果没找到,可以返回 null 或自定义默认值
    }
  }

  return labels;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值