Count the number of threads on a parent comment in ReactJS

怎甘沉沦 提交于 2019-12-06 06:31:11

You can do that using recursion.

  • Create a function getCount which takes object and count(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 add 1 to result which will be count of parent.
  • Finally use map() on obj.comments the call getCount on each of element with 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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!