I want to the update the object of id 21, make reply to false.
const arr = [ {id: 1, comment:'parent 01', parentId:null, reply:true, children:[{id: 11, comment:'child', reply:true, parentId:1, children:[{id: 21, comment:'super child ', reply:true,parentId:11 }] }] }, {id: 2, comment:'parent 02', reply:true, parentId:null } ]
result should be:
const arr = [ {id: 1, comment:'parent 01', parentId:null, reply:true, children:[{id: 11, comment:'child', reply:true, parentId:1, children:[{id: 21, comment:'super child ', reply:false,parentId:11 }] }] }, {id: 2, comment:'parent 02', reply:true, parentId:null } ]
[
{id: 1, comment:'parent 01', reply:true,parentId:null},
{id: 11, comment:'child', reply:true, parentId:1},
{id: 21, comment:'super child', reply:true, parentId:11},
{id: 2, comment:'parent 02', reply:true, parentId:null},
]
function to make this nested array:
function nestComments(commentList) {
const commentMap = {};
// move all the comments into a map of id => comment
commentList.forEach(comment => commentMap[comment.id] = comment);
// iterate over the comments again and correctly nest the children
commentList.forEach(comment => {
if(comment.parentId !== null) {
const parent = commentMap[comment.parentId];
(parent.children = parent.children || []).push(comment);
}
});
// filter the list to return a list of correctly nested comments
return commentList.filter(comment => {
return comment.parentId === null;
});
}