I have an array structure that represents categories with multiple levels:
[
{
"id": 5,
"parent_id": 3,
"name": "Fruits",
"parent": {
"id": 3,
"parent_id": 1,
"name": "Vegetables and fruits",
}
},
{
"id": 6,
"parent_id": 3,
"name": "Vegetables",
"parent": {
"id": 3,
"parent_id": 1,
"name": "Vegetables and fruits",
}
},
{
"id": 3,
"parent_id": null,
"name": "Vegetables and fruits",
"parent": null
},
]
My goal is to prepend a '-' (dash) to each child category based on its level within the hierarchy. For example, first-level categories get one dash '-', while third-level ones get two dashes '--'.
Is there a way to update the array's structure like this?
I've attempted some code snippet below:
const updateData = (data) => {
return data.map(item => {
if (item.parent_id != null) {
// Recursive logic might be needed here
item.name = `-${item.name }`;
}
return item;
})
}
Expected output after modification:
Vegetables and fruits
Drinks
-Fruits
-Vegetables
--Tomatoes
--Potatoes