计算ReactJS中父注释的线程数

时间:2019-05-14 03:34:55

标签: javascript reactjs recursion comments

我在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,但是我无法弄清楚如何正确地做到这一点。你能帮我吗?

1 个答案:

答案 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)