/**
* 给定一个键(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;
};

被折叠的 条评论
为什么被折叠?



