首页 > 解决方案 > 将嵌套对象合并到一层

问题描述

我在飞镖有以下课程

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

标签: recursiondartreduce

解决方案


我不完全确定您的数据结构,但我想您可以执行以下操作:

像这样扩展 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();

推荐阅读