1. 树型数据
const treeObj = [{ id: '0', name: '中国', children:[ { id: '1', name:'湖北省', children:[ { id: '1-1', name:'武汉市', children:[ { id: '1-1-1', name:'武昌区', }, ] }, ] }, { id: '2', name:'江苏省', children:[ { id: '2-1', name:'南京市', children:[ { id: '2-1-1', name:'玄武区', } ] }, { id: '2-2', name:'镇江市', children:[ { id: '2-2-1', name:'句容市', children: [ { id: '2-2-1-1', name:'下蜀镇' }, ] }, { id: '2-2-2', name:'京口区' }, ] }, ] }, { id: '3', name:'浙江省', } ] }];
2. js代码
function getMaxlevel (treeData) { let level = 0 let v = this let maxLevel = 0 function loop (data, level) { data.forEach(item => { item.level = level if (level > maxLevel) { maxLevel = level } if('children' in item){ if (item.children.length > 0) { loop(item.children, level + 1) } } }) } loop(treeData,1) console.log(maxLevel) } getMaxlevel(treeObj)