javascript - 计算 ReactJS 中父评论的线程数

标签 javascript reactjs recursion comments

我在 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/

相关文章:

php - 以所见即所得方式检查键入字符的长度

javascript - 如何阻止 ext-js 将 limit=25 添加到我的 JSON 查询中?

javascript - 如何在递归函数中维护变量?

sql - 如何使用递归查询跟踪以前的 ID?

javascript - Jquery 计算在应该返回 int 时返回 NaN

c# - 使用 ASP.NET MasterPage 时按正确顺序加载表

javascript - 如何在 react 中使用 getAttribute?

javascript - 如何从 API 读取图像数据并在 React Component 中渲染

javascript - 无法为 apexcharts 获取正确格式的数据

c# - 在 Windows 应用商店应用程序中递归获取文件和文件夹