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