JS中如何无需知晓路径即可获取JSON内最深层级的嵌套对象
未知层级路径时获取JSON嵌套结构最深层目标对象的实现方案
可以实现,不需要提前知道层级路径也能直接拿到目标响应对象,结合你给出的3条场景规则,以下是两种可直接使用的JavaScript实现方案:
方案1:循环逐层遍历(推荐)
逻辑简单无递归风险,适配你提到的「最高嵌套5层」的规则:
/** * @param {object} response 原始响应对象 * @param {string} targetKey 目标对象的固定共有键 * @returns {object} 目标响应对象 */ function getTargetObj(response, targetKey) { let current = response; // 最多遍历5次,匹配最高嵌套层数限制 for (let i = 0; i < 5; i++) { // 命中目标键直接返回 if (Object.hasOwn(current, targetKey)) return current; // 每层只有1个属性,直接取第一个属性的值进入下一层 const nextLevelKey = Object.keys(current)[0]; current = current[nextLevelKey]; } return current; } // 调用示例:假设目标对象的固定键为`result` const target = getTargetObj(response, 'result');
方案2:递归查找
适合后续嵌套层数可能调整的场景:
function getTargetObjRecursive(current, targetKey) { if (Object.hasOwn(current, targetKey)) return current; const nextLevelKey = Object.keys(current)[0]; return getTargetObjRecursive(current[nextLevelKey], targetKey); } // 调用示例 const target = getTargetObjRecursive(response, 'result');
补充说明
- 两种方案都不需要逐层编写链式访问代码,也不需要提前知晓每一层的路径名称
- 受限于「每层仅1个值」的规则,
Object.keys(current)[0]永远可以拿到唯一的下一层属性名,不会出现遍历偏差 - 如果不需要用固定键做终止判断,也可以修改终止条件为「当前值不是普通对象」,适配不同的目标对象特征。
内容的提问来源于stack exchange,提问作者tylermck
相关产品推荐
相关产品推荐

