สมมติว่าเรามีอาร์เรย์ของวัตถุเช่นนี้ -
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"
}
]; เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ของอ็อบเจ็กต์ดังกล่าว ฟังก์ชันควรใช้การเรียกซ้ำและแปลง 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"
}
}
]
}
]