हमारे पास ऑब्जेक्ट्स की एक सरणी है, जिसमें आगे इस तरह की नेस्टेड ऑब्जेक्ट्स हैं -
const arr = [{
id: 0, children: []
}, {
id: 1, children: [{
id: 2, children: []
}, {
id: 3, children: [{
id: 4, children: []
}]
}]
}]; हमारा काम एक पुनरावर्ती फ़ंक्शन लिखना है, जैसे कि असाइनडेप्थ () जो इस सरणी को लेता है और प्रत्येक नेस्टेड ऑब्जेक्ट को डेप्थ प्रॉपर्टी असाइन करता है। जैसे आईडी 0 वाली वस्तु की गहराई 0 होगी, आईडी 1 में भी गहराई 1 होगी, और चूंकि आईडी 2 और आईडी 3 आईडी 1 के अंदर नेस्टेड हैं, इसलिए उनकी गहराई 1 और आईडी 4 होगी, जो आईडी 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
}
]