- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Take in array of objects and convert the above JSON to a Tree-structure in JavaScript
Suppose, we have an array of objects like this −
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" } ];
We are required to write a JavaScript function that takes in one such array of objects. The function should then use recursion and convert the above JSON to a Tree−structure.
The Tree−structure would look like −
nodeStructure: { text: { name: "root3" }, children: [ { text: { name: "root2" } }, { text: { name: "root1" } } ] } };
Example
The code for this will be −
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));
Output
And the output in the console will be −
[ { "text": { "name": "root3" }, "children": [ { "text": { "name": "root2" } }, { "text": { "name": "root1" } } ] } ]
Advertisements