Answer the question
In order to leave comments, you need to log in
Add a function to create a response tree?
I am developing a frontend for a self-written forum. You need to write a function that will create a tree of responses in posts. This tree will then be recursively rendered by React (this is already done).
A typical post looks like this (removed elements that are not related to the task):
{
id: 2,
refTo: 1
comment: 'Комментарий'
}
const createReplyTree = (replyNode, thread = replyNode) => {
const tree = replyNode.map(i => {
const replies = thread.filter(item => item.refTo === i.id);
return {...i, replies: createReplyTree(replies, thread)};
});
return tree;
};
Answer the question
In order to leave comments, you need to log in
Iterating over an array with filtering will only work fast with a small number of elements, or when using memo or reselect, to ensure speed it is better to translate the array into a tree. Something like this.
const toTree = (arr, idAttr = 'id', parentAttr = 'parentId') => {
arr.sort((a, b) =>
(a[parentAttr] === b[idAttr] && 1) ||
(b[parentAttr] === a[idAttr] && -1) ||
0)
const tree = arr.reduce((tree, data) => {
data.children = []
tree[data[idAttr]] = data;
(tree[data[parentId]] || tree).children.push(data);
return tree
}, { children: [] }).children;
return tree
}
[{
id: 1,
comment: 'Комментарий',
children: [{
id: 2,
refTo: 1.
children: ...
}, {
id: 3.
refTo: 1,
}]
}, {...}]
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question