हमारे पास ऑब्जेक्ट्स का एक एरे है, जिसमें आगे नेस्टेड ऑब्जेक्ट्स हैं जैसे -
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 } ]