I have an array in React like this.
{
"comments":[
{
"id":1,
"comment_text":"asdasdadasds",
"author":"adsfas",
"post_id":1,
"children":[]
},
{
"id":2,
"comment_text":"idlsfgh",
"author":"asdsda",
"post_id":1,
"children":[
{
"id":3,
"comment_text":"fdsfdsfdsf",
"author":"sdfdsf",
"post_id":1,
"children":[
{
"id":4,
"comment_text":"fdsfdsfd",
"author":"sdfsdfdsfsd",
"post_id":1,
"children":[]
}
]
}
]
}
]
}
Now, I want to count the total number of replies on every parent comment. So the array output -
{
"result":[0, 2]
}
I am using Mongo, Express, React, NodeJS. I have tried of lot of things like using map in React but I am not able to figure out how to do it properly. Can you help me with this.
You can do that using recursion.
- Create a function
getCount
which takes object andcount
(previous count) as argument. - Check if the given object to that function doesn't have children then return
0
- Otherwise call the function recursively on all the children and return count of that child whose count is max using
Math.max()
. Also add1
to result which will be count of parent. - Finally use
map()
onobj.comments
the callgetCount
on each of element withcount=0
const obj = { "comments":[ { "id":1, "comment_text":"asdasdadasds", "author":"adsfas", "post_id":1, "children":[] }, { "id":2, "comment_text":"idlsfgh", "author":"asdsda", "post_id":1, "children":[ { "id":3, "comment_text":"fdsfdsfdsf", "author":"sdfdsf", "post_id":1, "children":[ { "id":4, "comment_text":"fdsfdsfd", "author":"sdfsdfdsfsd", "post_id":1, "children":[] } ] } ] } ] }
let res = obj.comments.map(x => getCount(x));
function getCount(obj,count=0){
if(!obj.children.length) return 0;
return Math.max(...obj.children.map(x => getCount(x)+1))
}
console.log(res)
来源:https://stackoverflow.com/questions/56122651/count-the-number-of-threads-on-a-parent-comment-in-reactjs