You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何统计JavaScript数组中category为card的truthy结果总数?

如何统计分类为card的story总数量

需求说明

需要统计给定数据结构中,所有category属性值为card的story条目总数。

现有数据结构

export const data = [
{
    id: "1",
    location: "Mexico",
    title: "Mexico",
    text: "Intro about Mexico",
    image: Mexique.png,
    stories: [
      {
        category: "card",
        title: "Yucatan",
        location: "Mexico",
        text: "Mexico, ....",
      },
      {
        category: "route",
        title: "My route",
        location: "Mexico",
        text: "....",
      },
   {
        category: "story",
        title: "My story",
        location: "Mexico",
        text: "....",
      },
    ],
  },
]

原有代码的问题

你之前的写法有两个核心错误:

  • storiesWithCategoryCard是每次内层循环里生成的单个布尔值(对应当前遍历的单个story的判断结果),不是存储所有判断结果的数组,布尔值本身没有filter方法,所以调用会报错
  • 嵌套使用map仅做了判断打印,没有把判断结果同步到外层计数器或者结果集合里,循环结束后拿不到所有判断结果

原有错误代码参考:

let nrOfCards = 0
data.map((card) => 
   card.stories.map((story) => {
      const storiesWithCategoryCard = story.category === 'card' 
      console.log(storiesWithCategoryCard)
})

// 这里会报错,因为storiesWithCategoryCard是单个布尔值,不是数组
nrOfCards = storiesWithCategoryCard.filter(Boolean).length

正确实现方案

方案1:计数器累加(逻辑直观易理解)

直接双层遍历数组,命中符合条件的story就给计数器加1即可:

let nrOfCards = 0
data.forEach(locationItem => {
  locationItem.stories.forEach(story => {
    if (story.category === 'card') {
      nrOfCards++
    }
  })
})

console.log(nrOfCards) // 输出符合预期的卡片总数

方案2:扁平化数组后统计(写法更简洁)

用flatMap把所有嵌套的stories拍平成一维数组,再筛选符合条件的项取长度:

const nrOfCards = data
  .flatMap(item => item.stories)
  .filter(story => story.category === 'card')
  .length

console.log(nrOfCards)

内容的提问来源于stack exchange,提问作者Ingeborg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.31 22:48:22