In my Vue.js project, the API data is returned in a flat array format. I need to restructure this data into a hierarchical tree structure by assigning parent IDs to their corresponding parent items.
I attempted to achieve this but ended up with an empty tree. Here is the code snippet:
convertToTree(data) {
const tree = [];
const mapped = {};
for (let i = 0; i < data.length; i += 1) {
mapped[data[i].id] = data[i];
mapped[data[i].id].children = [];
}
for (let i = 0; i < data.length; i += 1) {
if (mapped[data[i].parentId]) {
mapped[data[i].parentId].children.push(mapped[data[i]]);
} else {
tree.push(mapped[data[i]]);
}
}
return tree;
},
I am seeking solutions to resolve this issue. Your insights are highly appreciated.
Here is the sample data retrieved from the API:
{
"id": 1,
"parentId": 0
}, {
"id": 2,
"parentId": 0
}, {
"id": 3,
"parentId": 0
}, {
"id": 4,
"parentId": 3
}, {
"id": 5,
"parentId": 3
}, {
"id": 6,
"parentId": 4
}, {
"id": 7,
"parentId": 4
}, {
"id": 8,
"parentId": 5
}, {
"id": 9,
"parentId": 5
}, {
"id": 10,
"parentId": 0
}
This is the desired output structure:
items: [{
id: 1,
parentId: 0,
children: [{
id: 10,
parentId: 1,
}],
id: 2,
parentId: 0,
children: [],
id: 3,
parentId: 0,
children: [{
id: 4,
parentId: 3,
children: [{
id: 6,
parentId: 4,
children: []
},
{
id: 7,
parentId: 4,
children: []
},
{
id: 8,
parentId: 4,
children: []
}
]
},
{
id: 5,
parentId: 3,
children: [{
id: 9,
parentId: 5,
children: []
},
{
id: 10,
parentId: 5,
children: []
},
{
id: 11,
parentId: 5,
children: []
}
]
}
]
}]