繁体   English   中英

如何计算特定深度的json中的键数

[英]how to count the number of keys in a json at a specific depth

我有一个 json 文件,想使用来自特定深度的键的值执行计算。 在我的情况下,第一个值是:

json.children[0].children[0].children[0]

有没有办法在特定深度遍历 json 对象?

您可以使用树搜索来处理任何对象,包括反序列化的 json。 这个简单的函数返回给定深度的对象键的名称。 它不适用于将字符串作为值使用,但我认为您可以从这段代码中大致了解解决方案。

 json = { a: { aa: 123, bb: 456 }, b: {}, c: 123 } const checkAtDepth = (obj, depth) => { const result = []; const dfs = (node, maxDepth = 0, nodeName) => { if (maxDepth === 0) { result.push(nodeName); return; } Object.keys(node).forEach(key => { dfs(node[key], maxDepth-1, key); }) } dfs(obj, depth); return result; } console.log( checkAtDepth(json, 1) ) console.log( checkAtDepth(json, 2) ) console.log( checkAtDepth(json, 3) )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM