获取对象嵌套
const a = {
b: 1,
c() {},
d: {
e: 2,
f: {
g: 3,
h: {
i: {
j: 5
},
},
},
j: {
k: 5,
},
},
};
// 箭头函数命名方式
const testLevel = (param => {
const isObject = Object.prototype.toString.call(param) === '[object Object]';
if (!isObject) return 0;
const level = 1;
let childrenLevel = 0;
Object.entries(param)
.map(([key, value]) => {
const valueLevel = testLevel(value, level);
if (valueLevel > childrenLevel) childrenLevel = valueLevel;
});
num = level + childrenLevel
return level + childrenLevel;
})
testLevel(a)
console.log(num)
let num
获取数组嵌套
const treeData=[{
"label": "广东省",
"children": [{
"label": "梅州市",
"children": [{
"label": "兴宁市",
"children": [{
"label": "黄槐镇",
"children": [{
"label": "西埔村",
"children": []
},
{
"label": "宝龙村",
"children": []
},
{
"label": "双下村",
"children": []
},
{
"label": "双头村",
"children": []
},
{
"label": "槐东村",
"children": []
}
]
}]
}]
}]
}, {
"label": "一级2",
"children": []
}, {
"label": "一级3",
"children": []
}]
function getMaxFloor (treeData) {
let floor = 0
let v = this
let max = 0
function each (data, floor) {
data.forEach(e => {
e.floor = floor
if (floor > max) {
max = floor
}
if (e.children.length > 0) {
each(e.children, floor + 1)
}
})
}
each(treeData,1)
return max
}