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

JavaScript/TypeScript:按日期分组并聚合Rating的Ans值为数组

按日期分组提取评分数据

原始数据结构

[{
   Date: '01/11/2022',
   Questionnaire: [
   {Title: 'Rating', Ans: '5' },
   {Title: 'Comment', Ans: 'Awesome' }
   ]
},
{
   Date: '01/11/2022',
   Questionnaire: [
   {Title: 'Rating', Ans: '2' },
   {Title: 'Comment', Ans: 'Bad' }
   ]
},
{
   Date: '09/12/2022',
   Questionnaire: [
   {Title: 'Rating', Ans: '3' },
   {Title: 'Comment', Ans: 'Okay' }
   ]
}]

期望输出结构

[{
   Date: '01/11/2022',
   Ratings: ['5', '2']
},
{
   Date: '09/12/2022',
   Ratings: ['3']
}]

需求说明

  • 按Date字段对数据分组
  • 提取每个日期分组下,所有问卷中Title为Rating的Ans值,组成Ratings数组

实现示例(JavaScript)

可以利用数组的reduce方法完成分组和数据提取:

const originalData = [
  {
    Date: '01/11/2022',
    Questionnaire: [
      {Title: 'Rating', Ans: '5'},
      {Title: 'Comment', Ans: 'Awesome'}
    ]
  },
  {
    Date: '01/11/2022',
    Questionnaire: [
      {Title: 'Rating', Ans: '2'},
      {Title: 'Comment', Ans: 'Bad'}
    ]
  },
  {
    Date: '09/12/2022',
    Questionnaire: [
      {Title: 'Rating', Ans: '3'},
      {Title: 'Comment', Ans: 'Okay'}
    ]
  }
];

// 分组并提取评分
const groupedData = Object.values(originalData.reduce((result, currentItem) => {
  // 获取当前项的评分答案
  const rating = currentItem.Questionnaire.find(q => q.Title === 'Rating')?.Ans;
  
  // 如果当前日期还没在结果中,初始化分组
  if (!result[currentItem.Date]) {
    result[currentItem.Date] = {
      Date: currentItem.Date,
      Ratings: []
    };
  }
  
  // 若找到评分则添加到对应分组的Ratings数组
  if (rating) {
    result[currentItem.Date].Ratings.push(rating);
  }
  
  return result;
}, {}));

console.log(groupedData);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 01:45:36