I am currently facing a challenge with handling a complex json file using javascript to structure it hierarchically. My goal is to convert an array of objects into a deeply nested array, where there can be multiple divNames with varying categories and subcategories.
Here is the initial array of objects:
[
{
divName: "ABC",
divId: 123,
catName: "XYZ",
catId: 456,
subCatName: "PQR"
subCatId: 781
},
{
divName: "ABC",
divId: 123,
catName: "YQP",
catId: 281,
subCatName: "FYI"
subCatId: 231
},
{
divName: "ABC",
divId: 123,
catName: "XYZ",
catId: 456,
subCatName: "YAB"
subCatId: 587
}
]
The expected output should look like this:
[{divName: "ABC",
divId: 123
categories: [
{
catName: "XYZ",
catId: 456,
subCategories: [
{
subCatName: "PQR",
subCatID: 781
},
{
subCatName: "YAB",
subCatID: 587
}
]
},
{
catName: "YQP",
catId: 281,
subCategories: [
{
subCatName: "FYI"
subCatID: 231
}
]
}]
]
Currently, my progress on handling this conversion is as follows:
nonCompetitorData.map((data, idx) => {
if(idx === 0) {
downloadData.push({"divisionName": data.divisionName, "divisionId": data.divisionId});
} else {
if (!downloadData[0].categories) {
downloadData[0].categories = [];
downloadData[0].categories.push({
"categoryName": data.categoryName,
"categoryId": data.categoryId
})
} else {
if(downloadData[0].categories) {
if(!downloadData[0].categories.some(c => c.categoryName === data.categoryName)) {
downloadData[0].categories.push({
"categoryName": data.categoryName,
"categoryId": data.categoryId
})
}
}
downloadData[0].categories.forEach((cat, i) => {
if(!cat.subCategories) {
console.log("Categories",downloadData[0].categories[i]);
downloadData[0].categories[i].subCategories = [];
downloadData[0].categories[i].subCategories.push({
"subCategoryName": data.subCategoryName,
"subCategoryId": data.subCategoryId
});
} else {
if(cat.subCategories) {
if(!cat.subCategories.some(c => c.subCategoryName === data.subCategoryName)) {
downloadData[0].categories[i].subCategories.push({
"subCategoryName": data.subCategoryName,
"subCategoryId": data.subCategoryId
})
}
}
}
});
}
}
});
I am open to suggestions for a more efficient way to achieve this. Any insights?