如何实现递归获取JavaScript对象中指定属性的所有嵌套值?
递归获取对象嵌套属性值的问题分析与修复
需要实现一个JavaScript函数,接收对象和属性名,返回该属性的所有值(包括嵌套对象中的对应属性),并按规则整理结果:单个匹配值直接返回,多个匹配值返回数组。
示例对象与期望输出
示例对象:
let obj = { a: { b: "value of b", }, b: "another value of b", c: { d: [1, 2, 3], }, };
期望函数输出:
getDeepValuesProperty(obj, "a"); // { b: "value of b" } getDeepValuesProperty(obj, "b"); // ["value of b", "another value of b"] getDeepValuesProperty(obj, "d"); // [1, 2, 3]
原函数问题
最初编写的递归函数如下:
function getDeepValuesProperty(object, propertyName) { if (object[propertyName]) { return object[propertyName]; } else if (typeof object[propertyName] == "object") { return getDeepValuesProperty(object[propertyName], propertyName); } }
实际调用时不符合预期:
getDeepValuesProperty(obj, "b")仅返回最后一个匹配值getDeepValuesProperty(obj, "d")返回undefined
问题分析
- 未收集所有匹配项:函数找到第一个匹配属性就直接返回,没有遍历整个对象结构收集所有符合条件的值
- 递归逻辑错误:仅检查当前对象的
propertyName属性,未遍历对象所有键去递归查找嵌套结构 - 未处理数组场景:示例中
d属性是数组,原函数未遍历数组元素,导致无法匹配目标属性 - 对象判断不准确:
typeof null结果为"object",会触发错误的递归分支
修复后的函数
function getDeepValuesProperty(object, propertyName) { const result = []; function traverse(current) { // 跳过null、undefined及非对象/数组类型 if (current == null || typeof current !== 'object') { return; } // 当前对象包含目标属性则加入结果 if (propertyName in current) { result.push(current[propertyName]); } // 遍历所有键,递归处理嵌套结构 for (const key of Object.keys(current)) { traverse(current[key]); } } traverse(object); // 单个结果直接返回,多个结果返回数组 return result.length === 1 ? result[0] : result; }
测试验证
console.log(getDeepValuesProperty(obj, "a")); // { b: "value of b" } console.log(getDeepValuesProperty(obj, "b")); // ["value of b", "another value of b"] console.log(getDeepValuesProperty(obj, "d")); // [1, 2, 3]
内容的提问来源于stack exchange,提问作者TAHER El Mehdi
相关产品推荐
相关产品推荐

