如何统计 JavaScript 嵌套对象的嵌套级别?
我们有一个对象数组,其中嵌套了像这样类似的对象 −
const arr = [{
id: 0, children: []
}, {
id: 1, children: [{
id: 2, children: []
}, {
id: 3, children: [{
id: 4, children: []
}]
}]
}];我们的工作是编写一个递归函数,比如 assignDepth(),它接受这个数组,并为每个嵌套对象分配 depth 属性。比如,id 为 0 的对象深度为 0,id 为 1 的深度也是 1,因为 id 为 2 和 id 为 3 嵌套在 id 为 1 中,所以它们的深度为 1,而 id 为 4 进一步嵌套在 id 为 3 中,所以深度为 2。
因此,让我们编写这个函数的代码。这是一个简单的递归函数,它会不断迭代子对象直到到达数组的末尾 −
示例
const arr = [{
id: 0, children: []
}, {
id: 1, children: [{
id: 2, children: []
}, {
id: 3, children: [{
id: 4, children: []
}]
}]
}];
const assignDepth = (arr, depth = 0, index = 0) => {
if(index < arr.length){
arr[index].depth = depth;
if(arr[index].children.length){
return assignDepth(arr[index].children, depth+1, 0);
};
return assignDepth(arr, depth, index+1);
};
return;
};
assignDepth(arr);
console.log(JSON.stringify(arr, undefined, 4));输出
控制台的输出如下 −
[
{
"id": 0,
"children": [],
"depth": 0
},
{
"id": 1,
"children": [
{
"id": 2,
"children": [],
"depth": 1
},
{
"id": 3,
"children": [
{
"id": 4,
"children": [],
"depth": 2
}
],
"depth": 1
}
],
"depth": 0
}
]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP