重新排列对象数组,以便将答复添加到特定父对象



我有一个Object数组。它有两个属性-commentID和parentID。我想以这样一种方式安排它,即具有parentID的评论应该作为主评论的回复出现。回复的数量没有限制。嵌套可以扩展到任何级别。

我目前使用的角度版本是Angular9。我无法编辑或修改API的响应。我需要在Angular端处理这个。

**Array I am getting from API** : [
{
"description":"Comment Creation",
"id":1,
"parentCommentId":null,
"postId":1,
"user_id":2
},
{
"description":"Comment Creation",
"id":2,
"parentCommentId":null,
"postId":1,
"user_id":2
},
{
"description":"Comment Creation",
"id":3,
"parentCommentId":1,
"postId":1,
"user_id":2
},
{
"description":"Comment Creation",
"id":4,
"parentCommentId":3,
"postId":1,
"user_id":2
}
]
**Array I need** : [
{
"description":"Comment Creation",
"id":1,
"parentCommentId":null,
"postId":1,
"user_id":2,
"replies":[
{
"description":"Comment Creation",
"id":3,
"parentCommentId":1,
"postId":1,
"user_id":2,
"replies":[
{
"description":"Comment Creation",
"id":4,
"parentCommentId":3,
"postId":1,
"user_id":2,
"replies":[

]
}
]
}
]
},
{
"description":"Comment Creation",
"id":2,
"parentCommentId":null,
"postId":1,
"user_id":2,
"replies":[

]
}
]

我在谷歌上发现了一个非常有用的函数,只需少量修改就完成了它的工作。

const getNestedReplies = (topLevelComments, parentCommentId = null) => {
const nestedComments = [];
for (const i in topLevelComments) {
if (topLevelComments[i].parentCommentId === parentCommentId) {
const replies = getNestedReplies(topLevelComments, topLevelComments[i].id);
if (replies.length) {
topLevelComments[i].replies = replies;
}
nestedComments.push(topLevelComments[i]);
}
}
return nestedComments;
};

最新更新