我在React中有一个这样的数组。
@Test
public void testRemoveStudentFromEmptyGroup() {
// have created a Student: FRED and a Group: ADMINS
// Have not created any mapping for Group and ADMINS, so currently getStudentsInGroup(ADMINS) will return an empty Set<Student>
service.removeStudent(FRED, ADMINS);
assertTrue("ADMINS group is empty. Do nothing", service.getStudentsInGroup(ADMINS).size() == 0);
}
现在,我想计算每个父注释的答复总数。所以数组输出-
{
"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":[]
}
]
}
]
}
]
}
我正在使用Mongo,Express,React,NodeJS。我已经尝试过很多事情,例如在React中使用map,但是我无法弄清楚如何正确地做到这一点。你能帮我吗?
答案 0 :(得分:2)
您可以使用递归来实现。
getCount
,该函数将对象和count
(先前的计数)作为参数。0
Math.max()
返回该子项的最大计数。此外,将1
添加到结果中,该结果将作为父项的计数。
map()
上对obj.comments
的每个元素使用getCount
调用count=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)