如何实现按嵌套键列表检索并返回目标子对象的JavaScript函数?
扩展问题:按嵌套键路径查找对象子项
此问题源于原有讨论,因对话超出原问题范围,故提出扩展问题。
给定数据
{ "tabs-3": { "Collection A": { "Level 2": { "Data A": { "tab3graph25": { "30/04": 21750, "31/03": 19428, "29/05": 20955 } } } }, "Collection B": { "Level 2": { "Data A": { "tab3graph33": { "30/04": 56863, "31/03": 62298, "29/05": 56044 } } } }, "Collection C": { "Level 2": { "Data A": { "tab3graph40": { "30/04": 56044, "31/03": 62298, "29/05": 56863 } } } } } }
需求说明
编写函数接收以下两个参数:
- 待搜索的根对象(如示例中
"tabs-3"对应的对象) - 由嵌套键组成的搜索路径(例如
["Collection B", "Level 2", "Data A"])
最终返回该路径下的直接子对象(示例中即{ tab3graph33: { ...values... } })。
参考初始实现
function searchObjectForValues(obj, searchList) { var matchingObjects = {}; function recursiveSearch(currentObj, path) { if (typeof currentObj === 'object' && currentObj !== null) { for (var key in currentObj) { if (currentObj.hasOwnProperty(key)) { var value = currentObj[key]; var currentPath = path.concat(key); if (searchList.includes(key)) { matchingObjects[key] = currentObj[key]; } recursiveSearch(value, currentPath); } } } } recursiveSearch(obj, []); return matchingObjects; }
优雅实现方案
以下实现通过递归逐层定位路径,逻辑简洁且高效:
function getNestedChild(obj, path) { // 路径为空时直接返回当前对象 if (path.length === 0) return obj; // 解构取出当前层级的键和剩余路径 const [currentKey, ...remainingPath] = path; // 若当前对象不存在或无对应键,返回null if (!obj || !(currentKey in obj)) return null; // 递归处理下一层级 return getNestedChild(obj[currentKey], remainingPath); } // 使用示例 const rawData = {"tabs-3": { /* 上述完整数据 */ }}; const targetRoot = rawData["tabs-3"]; const searchPath = ["Collection B", "Level 2", "Data A"]; const result = getNestedChild(targetRoot, searchPath); console.log(result); // 输出:{ tab3graph33: { "30/04": 56863, "31/03": 62298, "29/05": 56044 } }
实现优势
- 仅沿指定路径遍历,避免无意义的全局递归搜索
- 提前处理边界情况(路径为空、键不存在),鲁棒性更强
- 使用ES6解构语法,代码简洁易读
内容的提问来源于stack exchange,提问作者NFSBuff
相关产品推荐
相关产品推荐

