JavaScript中如何遍历包含数组属性的对象?
遍历嵌套对象(含数组)的解决方案
嘿,当你的对象里嵌套了数组和子对象时,单层的Object.keys遍历就不够用啦,这时候我们可以用递归遍历的方式,自动处理所有层级的嵌套结构。下面给你几种实用的实现方式:
1. 基础版:遍历并输出所有值
这个版本会递归遍历对象的每一个属性,遇到数组或子对象就继续深入,直到找到基本类型的值(字符串、数字等)并打印:
function traverseObject(obj) { // 先处理数组类型 if (Array.isArray(obj)) { obj.forEach(item => traverseObject(item)); return; } // 处理对象类型(注意排除null,因为typeof null会返回"object") if (typeof obj === 'object' && obj !== null) { for (const key of Object.keys(obj)) { traverseObject(obj[key]); } return; } // 基本类型直接输出 console.log(obj); } // 测试你的person对象 const person = { name: "John", lastName: "Doe", age: 31, address: [{ street: "A Street Name", number: 190, apartment: 13 }] }; traverseObject(person);
运行后会输出:
John Doe 31 A Street Name 190 13
2. 进阶版:保留键路径的遍历
如果需要知道每个值对应的完整路径(比如address[0].street),可以修改函数来追踪键的层级:
function traverseObjectWithPaths(obj, parentPath = '') { if (Array.isArray(obj)) { obj.forEach((item, index) => { const arrayPath = parentPath ? `${parentPath}[${index}]` : `[${index}]`; traverseObjectWithPaths(item, arrayPath); }); return; } if (typeof obj === 'object' && obj !== null) { for (const key of Object.keys(obj)) { const currentPath = parentPath ? `${parentPath}.${key}` : key; traverseObjectWithPaths(obj[key], currentPath); } return; } console.log(`${parentPath}: ${obj}`); } traverseObjectWithPaths(person);
运行后会输出:
name: John lastName: Doe age: 31 address[0].street: A Street Name address[0].number: 190 address[0].apartment: 13
3. 安全版:处理循环引用
如果你的对象存在循环引用(比如person.self = person),递归会陷入无限循环导致栈溢出。这时候可以用WeakSet来记录已访问过的对象,避免重复处理:
function traverseObjectSafely(obj, parentPath = '', visited = new WeakSet()) { if (Array.isArray(obj)) { if (visited.has(obj)) return; visited.add(obj); obj.forEach((item, index) => { const arrayPath = parentPath ? `${parentPath}[${index}]` : `[${index}]`; traverseObjectSafely(item, arrayPath, visited); }); return; } if (typeof obj === 'object' && obj !== null) { if (visited.has(obj)) return; visited.add(obj); for (const key of Object.keys(obj)) { const currentPath = parentPath ? `${parentPath}.${key}` : key; traverseObjectSafely(obj[key], currentPath, visited); } return; } console.log(`${parentPath}: ${obj}`); }
这个版本能安全处理带循环引用的对象,不会出现栈溢出问题。
内容的提问来源于stack exchange,提问作者Marcello Fabrizio
相关产品推荐
相关产品推荐

