MongoDB中如何通过ID获取对象数组内的二级嵌套对象?
通过ID获取嵌套JSON结构中的完整对象
数据库结构
[ { "title": "man", "articlesType": [ { "title": "shoes", "articles": [ { "title": "shoes1", "id": "randomId" }, { "title": "shoes2", "id": "alsoRandomId" } ] } ] }, { "title": "woman", "articlesType": [ { "title": "pants", "articles": [ { "title": "pants1", "id": "anotherRandomId" }, { "title": "pants1", "id": "justId" } ] } ] } ]
期望结果
{ "title": "shoes2", "id": "alsoRandomId" }
解决方案
可以通过ID获取目标对象,针对你给出的固定嵌套结构,直接逐层遍历查找即可;如果结构可能有变化或层级更深,用递归遍历更通用。以下是两种实现示例(以JavaScript为例):
针对固定结构的遍历
function findArticleById(data, targetId) { // 遍历外层分类数组 for (const category of data) { // 遍历分类下的类型数组 for (const type of category.articlesType) { // 在文章数组中匹配ID const matched = type.articles.find(item => item.id === targetId); if (matched) return matched; } } return null; } // 调用:传入你的数据库数据和目标ID const result = findArticleById(你的数据库数据, "alsoRandomId"); console.log(result);
通用递归遍历(适配任意嵌套结构)
function findObjectById(obj, targetId) { // 当前对象是目标则返回 if (obj?.id === targetId) return obj; // 数组则遍历每个元素 if (Array.isArray(obj)) { for (const item of obj) { const res = findObjectById(item, targetId); if (res) return res; } } // 对象则遍历所有属性值 else if (typeof obj === 'object' && obj !== null) { for (const key in obj) { const res = findObjectById(obj[key], targetId); if (res) return res; } } return null; } // 调用:传入你的数据库数据和目标ID const result = findObjectById(你的数据库数据, "alsoRandomId"); console.log(result);
内容的提问来源于stack exchange,提问作者pope
相关产品推荐
相关产品推荐

