recursion - 将嵌套对象合并到一层
问题描述
我在飞镖有以下课程
class PostComment {
int id;
int title;
int parentCommentId;
List<PostComment> replies;
}
我从 api 收到的数据返回单个数组中的所有评论(无论在什么级别)。parentCommentId 用于指向回复的父级。要将这些数据转换为嵌套结构,我会这样做
void toNestedComments({List<PostComment> comments}) {
comments.forEach((postComment) {
if (postComment.parentCommentId != null) {
PostComment parentComment = comments.firstWhere((comment) => comment.id == postComment.parentCommentId, orElse: () => null);
parentComment.replies.add(postComment);
}
});
comments.removeWhere((c) => c.parentCommentId != null);
}
使用此代码,我得到以下结构中的注释数组。
Post 1
- Post 11
- Post 12
- Post 121
- Post 122
- Post 13
Post 2
- Post 21
- Post 211
但是 UI 要求数据如下所示。
Post 1
- Post 11
- Post 12
- Post 121
- Post 122
- Post 13
Post 2
- Post 21
- Post 211
您建议对上述功能进行什么样的修改以实现上述结构?
当前代码和数据结构位于https://dartpad.dartlang.org/6231828b3ea9dc1e956e87353394dae7
解决方案
我不完全确定您的数据结构,但我想您可以执行以下操作:
像这样扩展 PostComment 类:
class PostComment {
int id;
int title;
int parentCommentId;
List<PostComment> replies = [];
Iterable<PostComment> thisAndNestedReplies() sync* {
yield this;
for (var reply in replies) {
yield* reply.thisAndNestedReplies();
}
}
}
然后你可以执行以下操作(我仍然使用你的方法来获取嵌套数据结构):
toNestedComments(comments: comments);
var newList = comments
.where((postComment) => postComment.parentCommentId == null)
.expand((postComment) => postComment.thisAndNestedReplies()).toList();
推荐阅读
- typescript - 打字稿中的“in”关键字有什么作用?
- fpga - 仅使用按位运算是 100 的倍数
- firebase - 批处理和承诺之间的区别
- dns - 单个 AD 森林 - 开发和生产环境
- openldap - OpenLDAP 自定义属性:“未定义的属性类型”
- sql-server - 尝试运行 SSIS 作业时引发访问被拒绝错误
- android - Facebook AppLinking
- reactjs - 我可以在没有 jQuery 的情况下使用 bootstrap 4 模式吗?
- java - 引发 NullPointerException,即使它不是 NULL
- highcharts - 如何使用 highcharts 调整树形图中矩形的大小