我在 React 中有一个像这样的数组。
{
"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":[]
}
]
}
]
}
]
}
现在,我想统计每条家长评论的回复总数。所以数组输出 -
{
"result":[0, 2]
}
我正在使用 Mongo、Express、React、NodeJS。我尝试过很多事情,比如在 React 中使用 map ,但我不知道如何正确地做到这一点。你能帮我解决这个问题吗?
最佳答案
您可以使用递归来做到这一点。
- 创建一个函数
getCount
,它将对象和count
(上一个计数)作为参数。 - 检查该函数的给定对象是否没有子对象,然后返回
0
- 否则,对所有子项递归调用该函数,并使用
Math.max()
返回计数为 max 的子项的计数。还要将1
添加到结果中,这将是父级的计数。 - 最后在
obj.comments
上使用map()
,对每个count=0
元素调用getCount
>
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)
关于javascript - 计算 ReactJS 中父评论的线程数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56122651/