in my vuejs project I'm working on, the information from the api comes in the form of a flat array. I need to edit this incoming data and convert it to the following format. For example, I need to arrange the parent id of an object to be the id of its parent item.
i tried this way but the tree is returning as empty
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;
},
How can I solve this problem, I am waiting for your ideas.
data from 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 how i want to edit data
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: [],
},
],
},
],
}, ],
children) can be formed with recursive function call.