- Trending Categories
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
Build tree array from JSON in JavaScript
Suppose, we have the following array in JavaScript −
const arr = [{ "code": "2", "name": "PENDING" }, { "code": "2.2", "name": "PENDING CHILDREN" }, { "code": "2.2.01.01", "name": "PENDING CHILDREN CHILDREN" }, { "code": "2.2.01.02", "name": "PENDING CHILDREN CHILDREN02" }, { "code": "1", "name": "ACTIVE" }, { "code": "1.1", "name": "ACTIVE CHILDREN" }, { "code": "1.1.01", "name": "ACTIVE CHILDREN CHILDREN" }];
We are required to write a JavaScript function that takes in one such array. The function should build a tree structure from this array based on the "name" property of objects.
Therefore, for the above array, the output should look something like this −
const output = [{ "code": "2", "name": "PENDING", "children": [{ "code": "2.2", "name": "PENDING CHILDREN", "children": [{ "code": "2.2.01.01", "name": "PENDING CHILDREN CHILDREN" }, { "code": "2.2.01.02", "name": "PENDING CHILDREN CHILDREN02" }] }] }, { "code": "1", "name": "ACTIVE", "children": [{ "code": "1.1", "name": "ACTIVE CHILDREN", "children": [{ "code": "1.1.01", "name": "ACTIVE CHILDREN CHILDREN" }] }] }];
Example
The code for this will be −
const arr = [{ "code": "2", "name": "PENDING" }, { "code": "2.2", "name": "PENDING CHILDREN" }, { "code": "2.2.01.01", "name": "PENDING CHILDREN CHILDREN" }, { "code": "2.2.01.02", "name": "PENDING CHILDREN CHILDREN02" }, { "code": "1", "name": "ACTIVE" }, { "code": "1.1", "name": "ACTIVE CHILDREN" }, { "code": "1.1.01", "name": "ACTIVE CHILDREN CHILDREN" }]; const transformToTree = (arr, root = '') => { let map = {}, last = [root], level = 0; map[root] = {}; arr.forEach(el => { let parent = root; while (level && last[level].length >= el.code.length) { level--; }; parent = last[level]; level++; last.length = level; last.push(el.code); map[el.code] = el; map[parent].children = map[parent].children || []; map[parent].children.push(el); }); return map[root].children; }; console.log(JSON.stringify(transformToTree(arr), undefined, 4));
Output
And the output in the console will be −
[ { "code": "2", "name": "PENDING", "children": [ { "code": "2.2", "name": "PENDING CHILDREN", "children": [ { "code": "2.2.01.01", "name": "PENDING CHILDREN CHILDREN" }, { "code": "2.2.01.02", "name": "PENDING CHILDREN CHILDREN02" } ] } ] }, { "code": "1", "name": "ACTIVE", "children": [ { "code": "1.1", "name": "ACTIVE CHILDREN", "children": [ { "code": "1.1.01", "name": "ACTIVE CHILDREN CHILDREN" } ] } ] } ]
Advertisements