In the process of developing a React app with TypeScript, I encountered a challenging task involving formatting a complex nested JSON object into a specific structure.
const data = {
"aaa": {
"aa": {
"xxx": {
"xxxx": {}
}
},
"ab": {
"xxx": {},
"xxxx": {
"xxxx": {}
},
"yyy": {
"yyyy": {},
"zzzz": {},
"kkkk": {}
}
}
},
"bbb": {
"": {}
}
}
To tackle this issue, I crafted the following code snippet.
function formatData(obj: any, level: number) {
let formattedData = '';
if (level === 0)
formattedData += '[';
for (let key in obj) {
if (typeof obj[key] === 'object') {
formattedData += '{"value":' + level + ',';
formattedData += '"label":"' + key + '",';
formattedData += '"children":[' + formatData(obj[key], level + 1) + '],';
} else {
formattedData += '"value":' + level + ',"label":' + key + '"children":{' + obj[key] + '}}]';
}
}
return formattedData;
}
Afterwards, I intended to parse this output using Json.parse(). However, I faced difficulties with proper formatting as the curly braces were not closed correctly and it raised an error regarding 'duplicate keys.' Can anyone provide assistance in resolving these issues?
[
{
"value": "aaa",
"label": "aaa",
"children": [
{
"value": "aa",
"label": "aa",
"children": [
{
"value": "xxx",
"label": "xxx",
"children": [
{
"value": "xxxx",
"label": "xxxx"
}
]
}
]
},
{
"value": "ab",
"label": "ab",
"children": [
{
"value": "xxx",
"label": "xxx"
},
{
"value": "xxxx",
"label": "xxxx",
"children": [
{
"value": "xxxx",
"label": "xxxx"
}
]
},
{
"value": "yyy",
"label": "yyy",
"children": [
{
"value": "yyyy",
"label": "yyyy"
},
{
"value": "zzzz",
"label": "zzzz"
},
{
"value": "kkkk",
"label": "kkkk"
}
]
}
]
}
]
},
{
"value": "bbb",
"label": "bbb",
"children": [
{
"value": "",
"label": ""
}
]
}
]