[英]Iterate through deeply Nested JavaScript object and get the keys path
在检索包含值的每个键的路径时,如何遍历深度嵌套的对象。
演示输入对象
{
nested: {
nested2: {
nested3: '123'
},
nested4: '456'
}
}
想要的输出
nested.nested2.nested3
nested.nested4
您可以通过保留堆栈引用来递归访问节点。 我通过添加一个数组示例修改了对象。
我只是用点分隔符连接路径,然后使用以下正则表达式将数字键转换为括号表示法。
/(?:\\.)(\\d+)(?![a-z_])/ig
我结合了一个不匹配的组(以一个点开头)和一个负前瞻(不在字母之前)。
或者,您可以使用以下表达式:
/(?:\\.)(\\d+)(?=\\.)/g
我用积极的前瞻替换了消极的前瞻。 我基本上颠倒了表达,这可能更适合这种情况。
const obj = { nested: { nested2: [ { nested3: '123' }, { nested4: '456' } ], nested5: '789' } }; const visitNodes = (obj, visitor, stack = []) => { if (typeof obj === 'object') { for (let key in obj) { visitNodes(obj[key], visitor, [...stack, key]); } } else { visitor(stack.join('.').replace(/(?:\\.)(\\d+)(?![a-z_])/ig, '[$1]'), obj); } } visitNodes(obj, (path, value) => console.log(`${path} = ${value}`));
这是使用Array.reduce
的简洁解决方案:
const obj = { nested: { nested2: { nested3: '123' }, nested4: '456' } }; const r = (e, c = "") => Object.keys(e).reduce((t, y) => Array.isArray(e[y]) ? t : "object" == typeof e[y] ? [...t, ...r(e[y], c + y + ".")] : [...t, c + y], []); var s = r(obj) console.log(s);
您将不得不通过对象的路径递归,直到它到达不是对象的东西,此时它应该记录到该点的路径。
var x = {
nested: {
nested2: {
nested3: '123'
},
nested4: '456'
}
};
const printPaths = (obj, parentPath) => {
if (typeof obj === "object" && !Array.isArray(obj)) {
const layerKeys = Object.keys(obj);
for (const ky of layerKeys) {
const newKey = parentPath ? `${parentPath}.${ky}` : ky;
printPaths(obj[ky], newKey);
}
} else if (parentPath) {
console.log(parentPath);
}
};
printPaths(x);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.