计算嵌套js对象中项目的长度

计算嵌套js对象中项目的长度

给定这样的数组,我将如何获得特定类别中所有图表的计数。每个类别可以有多个或没有组。

{
   "categories":[
      {
         "title":"category 1",
         "id":"cat1",
         "groups":[
            {
               "title":"group 1",
               "id":"grp1",
               "charts":[
                  {
                     "title":"chart 1",
                     "id":"chart1",
                     "type":"line"
                  }
               ]
            }
         ]
      },
      {
         "title":"category 2",
         "id":"cat2",
         "charts":[
            {
               "title":"chart 2",
               "id":"chart2",
               "type":"line"
            }
         ]
      },
      {
         "title":"category 3",
         "id":"cat3",
         "charts":[
            {
               "title":"chart 3",
               "id":"chart3",
               "type":"line"
            }
         ]
      }
   ]
}

最佳答案

一线好吗?

假设数据是您的JSON结构:

data.categories
    .map(c => [
        c.title,
        c.groups ?
            c.groups.map(g => g.charts.length).reduce((a, b) => a+b) :
            c.charts.length
    ])

关于javascript - 计算嵌套js对象中项目的长度,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40524782/

10-10 05:32