I have an array of object. Each item has a paret id mentioned. I want to create a nested object where it nesting goes on as much as the subcategories. Input and expected output given below. How can I achieve this with plain JS?
var inputArr = [
{
category_id: 1,
parent_category_id: 3,
title: "category1"
},
{
category_id: 2,
parent_category_id: 1,
title: "category2"
},
{
category_id: 3,
title: "category3"
},
{
category_id: 4,
parent_category_id: 1,
title: "category4"
},
{
category_id: 5,
parent_category_id: 2,
title: "category5"
}
]
var expectedOutput = {
category_id: 3,
title: "category3",
subcategories: [
{
category_id: 1,
subcategories: [
{
category_id: 2,
title: "category2",
subcategories: [
{
category_id: 5,
title: "category5"
}
]
},
{
category_id: 4,
title: "category4"
}
]
}
]
}