代码之家  ›  专栏  ›  技术社区  ›  c6754

有没有办法用normalizer保持递归子顺序?

  •  0
  • c6754  · 技术社区  · 7 年前

    我正在从服务器检索已排序的注释数组。每条评论都有 comment.children 属性,它也是其他注释的排序数组。这些可以嵌套 n 很深。例如:

    const nestedComments = [
      {
        id: 1,
        body: "parent comment",
        children: [
            {
              id: 4,
              body: 'child comment',
              children: [
                {
                  id: 7,
                  body: 'grandchild comment #1',
                  children: [],
                },
                {
                  id: 6,
                  body: 'grandchild comment #2',
                  children: [],
                },
                {
                  id: 5,
                  body: 'grandchild comment #3',
                  children: [],
                },
              ]
            },
            {
              id: 3,
              body: 'second child comment',
              children: []
            }
        ],
      },
      {
        id: 8,
        body: 'parent comment #2',
        children: []
      },
    ];
    

    然后我使用normalizer库对其进行规范化,如下所示:

    const commentSchema = new schema.Entity('comments');
    const commentListSchema = new schema.Array(commentSchema);
    commentSchema.define({children: commentListSchema});
    const normalizedComments = normalize(nestedComments, commentListSchema);
    

    结果与预期差不多:

    {
      entities: {
        // All of the comments ordered their id's, this is fine and what I want
      },
      results: [1,8] // understandable but not what I want
    }
    

    因此,它保留根注释的顺序,但对嵌套的子注释不做任何操作。有没有办法让每一组兄弟姐妹都有自己的 results 阵列?像这样的东西:

    results: [[1,8], [4,3], [7,6,5]]; 
    

    或者也许有更好的方法来保存这些信息,我也很高兴听到这些。

    1 回复  |  直到 7 年前
        1
  •  0
  •   c6754    7 年前

    结果中已经给出了对我有用的答案。实体中的注释按原始顺序存储子ID的数组。

    entities: {
      {
        id: 1,
        body: 'parent comment',
        children: [4,3]
      },
      ...
      {
        id: 4,
        body: 'child comment',
        children: [7,6,5],
      },
      ...
    }