เรามีอาร์เรย์ของอ็อบเจ็กต์ ซึ่งยังมีอ็อบเจ็กต์ที่ซ้อนกันแบบนี้อีก -
const arr = [{
id: 0, children: []
}, {
id: 1, children: [{
id: 2, children: []
}, {
id: 3, children: [{
id: 4, children: []
}]
}]
}]; งานของเราคือการเขียนฟังก์ชันแบบเรียกซ้ำ พูด assignDepth() ที่ใช้ในอาร์เรย์นี้และกำหนดคุณสมบัติเชิงลึกให้กับแต่ละอ็อบเจ็กต์ที่ซ้อนกัน เช่นเดียวกับวัตถุที่มี 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
}
]