मान लीजिए, हमारे पास इस तरह की वस्तुओं की एक सरणी है -
const arr = [
{
"parentIndex": '0' ,
"childIndex": '3' ,
"parent": "ROOT",
"child": "root3"
},
{
"parentIndex": '3' ,
"childIndex": '2' ,
"parent": "root3" ,
"child": "root2"
},
{
"parentIndex": '3' ,
"childIndex": '1' ,
"parent": "root3" ,
"child": "root1"
}
]; हमें एक जावास्क्रिप्ट फ़ंक्शन लिखना आवश्यक है जो वस्तुओं की एक ऐसी सरणी लेता है। फिर फ़ंक्शन को रिकर्सन का उपयोग करना चाहिए और उपरोक्त JSON को ट्री-स्ट्रक्चर में बदलना चाहिए।
पेड़ की संरचना कुछ इस तरह दिखेगी -
nodeStructure: {
text: { name: "root3" },
children: [
{
text: { name: "root2" }
},
{
text: { name: "root1" }
}
]
}
}; उदाहरण
इसके लिए कोड होगा -
const arr = [
{
"parentIndex": '0' ,
"childIndex": '3' ,
"parent": "ROOT",
"child": "root3"
},
{
"parentIndex": '3' ,
"childIndex": '2' ,
"parent": "root3" ,
"child": "root2"
},
{
"parentIndex": '3' ,
"childIndex": '1' ,
"parent": "root3" ,
"child": "root1"
}
];
const partial = (arr = [], condition) => {
const result = [];
for (let i = 0; i < arr.length; i++) {
if(condition(arr[i])){
result.push(arr[i]);
}
}
return result;
}
const findNodes = (parentKey,items) => {
let subItems = partial(items, n => n.parent === parentKey);
const result = [];
for (let i = 0; i < subItems.length; i++) {
let subItem = subItems[i];
let resultItem = {
text: {name:subItem.child}
};
let kids = findNodes(subItem.child , items);
if(kids.length){
resultItem.children = kids;
}
result.push(resultItem);
}
return result;
}
console.log(JSON.stringify(findNodes('ROOT', arr), undefined, 4)); आउटपुट
और कंसोल में आउटपुट होगा -
[
{
"text": {
"name": "root3"
},
"children": [
{
"text": {
"name": "root2"
}
},
{
"text": {
"name": "root1"
}
}
]
}
]