Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert JSON to another JSON format with recursion JavaScript
Suppose, we have the following JSON object −
const obj = {
"context": {
"device": {
"localeCountryCode": "AX",
"datetime": "3047-09-29T07:09:52.498Z"
},
"currentLocation": {
"country": "KM",
"lon": -78789486,
}
}
};
We are required to write a JavaScript recursive function that initially takes in one such array.The function should split the above object into a "label" - "children" format.
Therefore, the output for the above object should look like −
const output = {
"label": "context",
"children": [
{
"label": "device",
"children": [
{
"label": "localeCountryCode"
},
{
"label": "datetime"
}
]
},
{
"label": "currentLocation",
"children": [
{
"label": "country"
},
{
"label": "lon"
}
]
}
]
}
The code for this will be −
Example
const obj = {
"context": {
"device": {
"localeCountryCode": "AX",
"datetime": "3047-09-29T07:09:52.498Z"
},
"currentLocation": {
"country": "KM",
"lon": -78789486,
}
}
};
const transformObject = (obj = {}) => {
if (obj && typeof obj === 'object') {
return Object.keys(obj).map((el) => {
let children = transformObject(obj[el]); return children ? {
label: el, children: children } : {
label: el
};
});
};
};
console.log(JSON.stringify(transformObject(obj), undefined, 4));
Output
And the output in the console will be −
[
{
"label": "context",
"children": [
{
"label": "device",
"children": [
{
"label": "localeCountryCode"
},
{
"label": "datetime"
}
]
},
{
"label": "currentLocation",
"children": [
{
"label": "country"
},
{
"label": "lon"
}
]
}
]
}
]Advertisements