I have a project with javascript.in my project i have a flat array with this structure
[{
id: 'p-124',
name: 'Pouya',
comment: 'harmoqe radif shod khabar bede',
parentId: 'b-143',
}, {
id: 'p-123',
name: 'Pouya',
comment: 'soala ro didi?',
parentId: null,
}, {
id: 'b-143',
name: 'Arash',
comment: 'alan daram mikhunam yekam edit mikonam',
parentId: 'p-123',
}, {
id: 'a-143',
name: 'Arash',
comment: 'yekam taqir dadam radife',
parentId: 'p-123',
}]
I want convert this array to nested array according parentId so in this case for each element i have an array called children and if element A forexample has id='5' and element B has parentId='5' then I put it into children of element A
so for this input i want this output
[{
id: 'p-123',
name: 'Pouya',
comment: 'soala ro didi?',
children: [{
id: 'b-143',
name: 'Arash',
comment: 'alan daram mikhunam yekam edit mikonam',
children: [{
id: 'p-124',
name: 'Pouya',
comment: 'harmoqe radif shod khabar bede',
children: [],
}],
}, {
id: 'a-143',
name: 'Arash',
comment: 'yekam taqir dadam radife',
children: []
}],
}]
I try alot for solving this problem but I can't. this is my code
function solve(arrOfApplicationScores) {
let result = [];
arrOfApplicationScores.forEach((comment, index) => {
if (comment.parentId == null) {
result = [{
id: comment.id,
name: comment.name,
comment: comment.comment,
children: []
}];
arrOfApplicationScores.splice(index, 1);
}
});
result.forEach((res, index) => {
arrOfApplicationScores.forEach((comment, index) => {
if (res.id === comment.parentId) {
res.children.push({
id:comment.id,
name:comment.name,
comment:comment.comment,
children:[]
});
arrOfApplicationScores.splice(index, 1);
}
});
});
console.log(result,'RES',arrOfApplicationScores);
}
solve([{
id: 'p-124',
name: 'Pouya',
comment: 'harmoqe radif shod khabar bede',
parentId: 'b-143',
}, {
id: 'p-123',
name: 'Pouya',
comment: 'soala ro didi?',
parentId: null,
}, {
id: 'b-143',
name: 'Arash',
comment: 'alan daram mikhunam yekam edit mikonam',
parentId: 'p-123',
}, {
id: 'a-143',
name: 'Arash',
comment: 'yekam taqir dadam radife',
parentId: 'p-123',
}])