Reputation: 887
I am retrieving a sorted array of comments from the server. Each comment has a comment.children
attribute that is also a sorted array of other comments. These can be nested n
deep. E.g:
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: []
},
];
Then I use the normalizr library to normalize it like this:
const commentSchema = new schema.Entity('comments');
const commentListSchema = new schema.Array(commentSchema);
commentSchema.define({children: commentListSchema});
const normalizedComments = normalize(nestedComments, commentListSchema);
The result is pretty much as expected:
{
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
}
So it preserves the order of the root comments but doesn't do anything for the nested child comments. Is there a way to do this so that each group of siblings has its own results
array? Something that looks like this:
results: [[1,8], [4,3], [7,6,5]];
Or maybe there is a better way to preserve that information and I'd appreciate hearing about that as well.
Upvotes: 0
Views: 549
Reputation: 887
The answer that will work for me was already present in the results. The comments in the entities stores an array of the children ids that is in the original order.
entities: {
{
id: 1,
body: 'parent comment',
children: [4,3]
},
...
{
id: 4,
body: 'child comment',
children: [7,6,5],
},
...
}
Upvotes: 1