I have an array of values and I want to convert them into nested objects if the category i.e 1st element exists then the next subcategories are pushed in this. Can we achieve this, I am beginner please help
for example:
const newCat = [
[
"Grocery", // category
"Food & Drink", // sub-category
"Snacks, Crisps and Sweets", // sub-sub-category
],
[
"Grocery",
"Canned, Dry & Packaged Food",
"Pickled Foods",
],
[
"Grocery",
"Food & Drink",
],
[
"Grocery",
"Food & Drink",
"Nuts, Dates & Dried Fruits",
],
[
"Grocery",
"World Specialities",
"India",
],
]
OUTPUT -
[
{
CategoryName: "Grocery",
SubCategories: [
{
CategoryName: "Food & Drink",
SubCategories: [
{
CategoryName: "Snacks, Crisps, and Sweets",
},
],
},
{
CategoryName: "Canned, Dry & Packaged Food",
SubCategories: [
{
CategoryName: "Pickled Foods",
},
],
},
],
}
]
function flatArray(arr) {
const result = [];
for (let item of arr) {
const [c1, c2, c3] = item;
const findC1 = result.find(c => c.categoryName === c1);
if (findC1) {
if (!c2) {
continue;
}
const findC2 = findC1.subCategorys.find(c => c.categoryName === c2);
if (findC2) {
if (!c3) {
continue;
}
findC2.subCategorys.push(c3);
} else {
findC1.subCategorys.push({
categoryName: c2,
subCategorys: [c3]
});
}
} else {
result.push({
categoryName: c1,
subCategorys: [
{
categoryName: c2,
subCategorys: [c3]
}
]
})
}
}
return result;
}
// Test case
const newCat = [
[
"Grocery", // category
"Food & Drink", // sub-category
"Snacks, Crisps and Sweets", // sub-sub-category
],
[
"Grocery",
"Canned, Dry & Packaged Food",
"Pickled Foods",
],
[
"Grocery",
"Food & Drink",
],
[
"Grocery",
"Food & Drink",
"Nuts, Dates & Dried Fruits",
],
[
"Grocery",
"World Specialities",
"India",
],
];
console.log(flatArray(newCat));