JavaScript:在树形的对象数组中,给定一个键(key)及其对应的值,寻找并返回该对象下另一个指定键的值。

/**
 * 给定一个键(key)及其对应的值,寻找并返回该对象下另一个指定键的值。
 *
 * @description
 * 该函数遍历给定的树形结构数组,尝试根据 `sourceKey` 和 `sourceKeyValue` 找到匹配的节点。
 * 如果匹配成功,则返回该节点下 `targetKey` 对应的值。如果当前节点有子节点,
 * 则会递归地在子节点中进行查找。若遍历完整个树形结构仍未找到匹配项,则最终返回 `undefined`。
 *
 * @function findValueByValue
 * @param {Record<string, any>[]} treeNodes - 待搜索的树形结构数组。
 * @param {string} sourceKey - 用于比较的源键名。
 * @param {(string | number)} sourceKeyValue - 源键对应的值,用于在树节点中匹配。
 * @param {string} targetKey - 需要返回的目标键名。
 *
 * @returns {string | number | undefined} - 查找到的目标键对应的值,未找到时返回 `undefined`。
 *
 */
export const findValueByValue = (
  treeNodes: Record<string, any>[],
  sourceKey: string,
  sourceKeyValue: string | number,
  targetKey: string
): string | number | undefined => {
  for (const node of treeNodes) {
    if (node[sourceKey] === sourceKeyValue) {
      return node[targetKey];
    }
    // 如果当前节点有子节点,继续在子节点中递归查找
    if (node.children && node.children.length > 0) {
      const target = findValueByValue(
        node.children,
        sourceKey,
        sourceKeyValue,
        targetKey
      );
      // 如果在子节点中找到了匹配项,直接返回结果
      if (target !== undefined) {
        return target;
      }
    }
  }
  // 如果遍历完所有节点都没有找到匹配项,返回 undefined
  return undefined;
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

保禄241225

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值