JavaScript如何从嵌套对象数组中查询指定Key对应的父级Key
实现代码
你可以用深度优先递归遍历实现,核心逻辑是遍历每个节点时优先检查它的直接子节点是否包含目标Key,匹配到就直接返回当前节点的Key,否则递归进入子节点查询:
function findParentKey(data, targetKey) { for (const node of data) { // 无有效子节点直接跳过 if (!Array.isArray(node.Children) || node.Children.length === 0) { continue } // 检查直接子节点是否存在目标Key const isChildTarget = node.Children.some(child => child.Key === targetKey) if (isChildTarget) { return node.Key } // 递归查询子节点的下级 const result = findParentKey(node.Children, targetKey) if (result) { return result } } // 未找到对应父节点返回null return null }
使用示例
const myData = [ { "Name": "Main Menu", "Key": "1", "Children": [ { "Name": "Sub Menu 1", "Key": "10", "Children": [ { "Name": "Very Sub Menu", "Key": "20", "Children": [] } ] } ] }, { "Name": "Main Menu 2", "Key": "2", "Children": [ { "Name": "Sub Menu 2", "Key": "11", "Children": [ { "Name": "Very Sub Menu 2", "Key": "21", "Children": [ { "Name": "Extra Small Menu", "Key": "30", "Children": [] } ] } ] } ] } ] console.log(findParentKey(myData, '10')) // 输出 '1' console.log(findParentKey(myData, '30')) // 输出 '21'
原有代码问题说明
- 字段名大小写不匹配:你的数据结构中字段为大写开头的
Key、Children,原代码使用小写key导致匹配不到对应值 filter方法的特性是返回符合条件的数组,天然会保留完整路径的所有层级节点,不适合只提取直接父节点的场景
内容的提问来源于stack exchange,提问作者Uğurcan Uçar
相关产品推荐
相关产品推荐

