I have an array as below: Top level category will have parent_category_id to be 0. Sub categories will have property of parent_category_id equal to the respective parent categories.
const categories = [
{
category_id: 1,
name: "Fashion",
parent_category_id: 0,
has_category: 2,
},
{
category_id: 2,
name: "Men's Fashion",
parent_category_id: 1,
has_category: 1,
},
{
category_id: 3,
name: "Men's Fashion - Shoes",
parent_category_id: 2,
has_category: null,
},
{
category_id: 4,
name: "Electronics",
parent_category_id: 0,
has_category: 1,
},
{
category_id: 5,
name: "mobile",
parent_category_id: 4,
has_category: 1,
},
{
category_id: 6,
name: "smart-phone",
parent_category_id: 5,
has_category: null,
},
{
category_id: 7,
name: "Womens's Fashion",
parent_category_id: 1,
has_category: null,
},
];
Expected result as follows:
const newArray = [
{
category_id: 1,
name: "Fashion",
parent_category_id: 0,
has_category: 2,
subCategory: [
{
category_id: 2,
name: "Men's Fashion",
parent_category_id: 1,
has_category: 1,
subCategory: [
{
category_id: 3,
name: "Men's Fashion - Shoes",
parent_category_id: 2,
has_category: null,
},
],
},
{
category_id: 7,
name: "Womens's Fashion",
parent_category_id: 1,
has_category: null,
},
],
},
{
category_id: 4,
name: "Electronics",
parent_category_id: 0,
has_category: 1,
subCategory: [
{
category_id: 5,
name: "mobile",
parent_category_id: 4,
has_category: 1,
subCategory: [
{
category_id: 6,
name: "smart-phone",
parent_category_id: 5,
has_category: null,
},
],
},
],
},
];
const findSubCategory = (arr, id) => {
let result = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i].parent_category_id === id) {
result.push(arr[i]);
}
}
return result;
};
let newArray = [];
for (let i = 0; i < categories.length; i++) {
if (categories[i].parent_category_id <= 0) {
let itemWithCategory = {
...categories[i],
};
itemWithCategory.subCategory = findSubCategory(
categories,
categories[i].category_id
);
newArray.push(itemWithCategory);
}
}
console.log(newArray);
Can any one help to get the expected result as above.
Thank you.