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

如何对对象数组按属性聚合过滤,整理为ChartJS折线图所需格式?

实现方案

直接用reduce结合临时映射对象实现,性能优于每次遍历filter的方式,代码如下:

const rawData = [
  {"page": "Page 1","date": "2021-10-05","visitors": 10},
  {"page": "Page 2","date": "2021-10-05","visitors": 20},
  {"page": "Page 3","date": "2021-10-05","visitors": 30},
  {"page": "Page 1","date": "2021-10-04","visitors": 40},
  {"page": "Page 2","date": "2021-10-04","visitors": 50},
  {"page": "Page 3","date": "2021-10-04","visitors": 60}
];

const chartData = Object.values(rawData.reduce((acc, cur) => {
  // 以页面名为唯一key做临时存储
  if (!acc[cur.page]) {
    acc[cur.page] = {
      page: cur.page,
      dates: [],
      numberOfVisits: []
    }
  }
  // 追加当前条目的日期、访客数到对应数组
  acc[cur.page].dates.push(cur.date)
  acc[cur.page].numberOfVisits.push(cur.visitors)
  return acc
}, {}))

运行后chartData就是你要求的目标格式。如果需要保证日期顺序,可额外加排序逻辑:

chartData.forEach(pageItem => {
  // 配对日期和访客数后按时间升序排序,避免数据错位
  const sortedPair = pageItem.dates
    .map((date, index) => ({ date, count: pageItem.numberOfVisits[index] }))
    .sort((a, b) => new Date(a.date) - new Date(b.date))
  pageItem.dates = sortedPair.map(item => item.date)
  pageItem.numberOfVisits = sortedPair.map(item => item.count)
})

内容的提问来源于stack exchange,提问作者Yacine Sidi Attallah

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 22:45:01