js获取多层json最深层级数

Heerey525
前端领域新星创作者
2018-08-23 04:02:30
如题,就是有个多层json对象,获取它的最深层级数
...全文
548 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
Heerey525 2018-08-23
  • 打赏
  • 举报
回复 1
引用 5 楼 jslang 的回复:

var num = 0;
function recursion(obj,k) {
num = Math.max(num,k);
console.log(k);
if (obj.list)
obj.list.forEach(function(v, i){
recursion(v,k+1);
});
}
recursion(data,1);
console.log("最深层级数"+num);


非常感谢大神,问题已解决,献上我的膝盖
天际的海浪 2018-08-23
  • 打赏
  • 举报
回复

var num = 0;
function recursion(obj,k) {
num = Math.max(num,k);
console.log(k);
if (obj.list)
obj.list.forEach(function(v, i){
recursion(v,k+1);
});
}
recursion(data,1);
console.log("最深层级数"+num);

Heerey525 2018-08-23
  • 打赏
  • 举报
回复
引用 2 楼 foren_whb 的回复:
这种结构,只能遍历

您好,能给我个demo吗
丰云 2018-08-23
  • 打赏
  • 举报
回复
如果用标准的树结构,就不会这么麻烦了
丰云 2018-08-23
  • 打赏
  • 举报
回复
这种结构,只能遍历
Heerey525 2018-08-23
  • 打赏
  • 举报
回复
var data={"list":[{"list":[{"list":[{"list":[{"list":[{"four":"4","one":"1","three":"3","two":"2"}],"value":"4"}],"value":"3"}],"value":"2"},{"list":[{"list":[{"list":[{"four":"4","one":"1","three":"3","two":"3"}],"value":"4"}],"value":"3"},{"list":[{"list":[{"four":"4","one":"1","three":"4","two":"3"},{"four":"4","one":"1","three":"4","two":"3"}],"value":"4"}],"value":"4"}],"value":"3"}],"value":"1"},{"list":[{"list":[{"list":[{"list":[{"four":"4","one":"2","three":"3","two":"2"}],"value":"4"}],"value":"3"}],"value":"2"}],"value":"2"},{"list":[{"list":[{"list":[{"list":[{"four":"4","one":"3","three":"3","two":"2"}],"value":"4"}],"value":"3"}],"value":"2"}],"value":"3"},{"list":[{"list":[{"list":[{"list":[{"four":"4","one":"4","three":"3","two":"2"}],"value":"4"}],"value":"3"}],"value":"2"}],"value":"4"}],"value":"root"}

87,964

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧