
本文介绍一种高效、递归的 JavaScript 方法,用于在任意深度的嵌套 JSON 对象中查找包含指定键(如 xpublisher)的第一个父对象,并完整返回该对象(而非仅值或路径)。
本文介绍一种高效、递归的 javascript 方法,用于在任意深度的嵌套 json 对象中查找包含指定键(如 `xpublisher`)的第一个父对象,并完整返回该对象(而非仅值或路径)。
在处理 Schema(如 OpenAPI 或 JSON Schema)等结构化配置数据时,常需根据某个元字段(例如自定义扩展字段 xpublisher)快速定位其所属的完整属性定义对象。由于这类数据往往嵌套多层,简单遍历 Object.keys() 或浅层查找无法满足需求——必须深入递归,同时保留上下文结构。
以下是一个简洁、健壮且可复用的递归搜索函数:
const findParent = (obj, key) => {
// 基础校验:非对象或 null/undefined 直接返回
if (!obj || typeof obj !== 'object') return undefined;
// 若当前对象自身拥有目标 key,立即返回该对象(即“父对象”)
if (key in obj) return obj;
// 否则递归检查所有子值(包括数组元素和对象属性值)
for (const value of Object.values(obj)) {
const parent = findParent(value, key);
if (parent !== undefined) return parent;
}
// 未找到,返回 undefined
return undefined;
};✅ 使用示例(基于你提供的 JSON 数据):
const data = {
type: "object",
title: "Scalars",
properties: {
stringProperty: {
description: "Property name's description (type is string)",
type: "string",
examples: ["example", "sample"],
xpublisher: ["Greg", "Tom"],
},
writeOnlyStringProperty: {
description: "Notice this only appears in the request.",
xpublisher: ["John", "Anna"],
type: "string",
writeOnly: true,
examples: ["example"],
},
minLengthString: {
xpublisher: ["Nancy", "Tim"],
description: "Property name's description (type is string)",
type: "string",
minLength: 4,
examples: ["example"],
},
}
};
// 查找第一个含 'xpublisher' 的父对象(即 stringProperty 的完整定义)
const result = findParent(data, 'xpublisher');
console.log(result);
// 输出:
// {
// description: "Property name's description (type is string)",
// type: "string",
// examples: ["example", "sample"],
// xpublisher: ["Greg", "Tom"]
// }? 关键设计说明:
- 函数返回的是包含目标键的最直接父对象,而非键值本身或路径;
- 使用
key in obj而非obj[key] !== undefined,避免因null或false等 falsy 值导致误判; -
Object.values()自动兼容对象与数组(若 JSON 中存在数组字段,也会被遍历); - 短路逻辑:一旦找到首个匹配项即终止递归,提升性能;
- 不修改原始数据,纯函数式,无副作用。
⚠️ 注意事项:
- 该方法返回第一个匹配的父对象(深度优先、先序遍历),如需全部匹配结果,可改为收集数组并返回
result数组; - 若目标键存在于顶层对象(如
data.xpublisher),会直接返回data; - 不支持
Symbol键或原型链上的属性(符合in操作符语义,聚焦自有属性)。
掌握此模式后,你可轻松适配其他类似场景,例如查找 x-deprecated、$ref、default 等语义化字段的宿主对象,大幅提升 JSON Schema 处理、表单生成或文档提取的开发效率。


















