计算 ReactJS 中父评论的线程数

Count the number of threads on a parent comment in ReactJS

我在 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 中使用地图,但我无法弄清楚如何正确地做到这一点。你能帮我解决这个问题吗?

你可以使用递归来做到这一点。

  • 创建一个函数 getCount,它将 object 和 count(先前的计数)作为参数。
  • 检查该函数的给定 object 是否没有 children 然后 return 0
  • 否则递归调用该函数对所有 child 的 children 和 return 计数,其计数为最大使用 Math.max()。还要将 1 添加到结果中,这将是 parent.
  • 的计数
  • 最后在 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)