如何統計 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