计算ReactJS中父注释的线程数 [英] Count the number of threads on a parent comment in ReactJS
本文介绍了计算ReactJS中父注释的线程数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在React中有这样一个数组。
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]
}
我正在使用Mongo,Express,React,NodeJS。我已经尝试了很多事情,例如在React中使用map,但是我无法弄清楚如何正确地做到这一点。
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.
- 创建一个函数
getCount
,该函数接受对象和count
(先前的计数) - 检查该函数的给定对象是否没有子对象,然后返回
0
- 否则,对所有子项递归调用该函数,并使用
Math.max()
返回该子项的最大计数。还要在结果中添加1
。 - 最后使用
map()$
obj.comments
上的c $ c>对每个具有count =的元素的调用
getCount
0
- 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)
这篇关于计算ReactJS中父注释的线程数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文