如何用JavaScript查找包含xpublisher字段的JSON父对象?
问题
我需要从以下JSON对象中查找所有包含xpublisher字段的父对象:
{ "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" ] } } }
预期找到的第一个目标父对象为:
stringProperty: { description: "Property name's description (type is string)", type: "string", examples: [ "example", "sample", ], xpublisher: [ "Greg", "Tom", ], },
我尝试了以下两种JavaScript函数,但只能找到键编号而非键名,无法正确获取目标对象:
第一种函数:
function getPublishers(obj, name) { let result = []; for (var key in obj) { let keyName = obj[key] console.log(keyName) if (obj.hasOwnProperty(key)) { if ("object" == typeof(obj[key])) { getPublishers(obj[key], name); } else if (key == name) { result.push(obj[key]); } } } return result; }
第二种函数:
function searchObject(obj, name) { let result = Object.keys(obj).find(k => obj[k][name]); return result; }
请问如何修改代码以正确获取包含xpublisher字段的父对象?
解决方案
问题分析
- 第一个函数逻辑偏差:递归调用未收集返回结果,且错误地去匹配字段本身,而非包含该字段的父对象;递归时也未传递父对象信息。
- 第二个函数局限性:仅返回第一个匹配的键名,只检查当前层级,无法处理嵌套结构,也不会返回完整的父对象。
获取所有符合条件的父对象
以下递归函数可收集所有包含目标字段的父对象(带键名):
function findParentObjectsWithField(obj, targetField) { const results = []; function traverse(currentObj) { for (const key in currentObj) { if (currentObj.hasOwnProperty(key)) { const value = currentObj[key]; // 检查当前值是否为对象且包含目标字段 if (typeof value === 'object' && value !== null && targetField in value) { results.push({ [key]: value }); } // 递归遍历嵌套对象 if (typeof value === 'object' && value !== null) { traverse(value); } } } } traverse(obj); return results; }
使用示例
调用方式:
const data = { /* 你的JSON数据 */ }; const matchedParents = findParentObjectsWithField(data, 'xpublisher'); console.log(matchedParents);
返回结果为数组,包含所有符合条件的父对象,第一个元素就是你预期的stringProperty对应的对象。
仅获取第一个匹配项
如果只需要第一个找到的父对象,可修改函数为:
function findFirstParentObjectWithField(obj, targetField) { function traverse(currentObj) { for (const key in currentObj) { if (currentObj.hasOwnProperty(key)) { const value = currentObj[key]; if (typeof value === 'object' && value !== null && targetField in value) { return { [key]: value }; } if (typeof value === 'object' && value !== null) { const result = traverse(value); if (result) return result; } } } return null; } return traverse(obj); }
内容的提问来源于stack exchange,提问作者Tim Morford
相关产品推荐
相关产品推荐

