对象计数数组出现并返回对象

时间:2021-04-23 09:53:35

标签: javascript

我想计算日期的所有出现次数并将它们分组,然后用计数计算这些日期的所有小时数。

这是我的数组:

var array = [{ date: '2021-04-28', hours: '05:30' },
  { date: '2021-04-28', hours: '05:30' },
  { date: '2021-04-28', hours: '03:00' },
  { date: '2021-04-20', hours: '10:00' },
  { date: '2021-04-20', hours: '10:00' },
  { date: '2021-04-20', hours: '10:00' },
  { date: '2021-05-04', hours: null },
  { date: '2021-05-05', hours: null }
]

它应该返回一个对象:

var object =  {
       2021-04-28 : {
       count : 3, // count
       hours : {
       05:30 : 2,// count
       03:00 : 1
       }
      },
      2021-04-20 : {
       count : 3, // count
       hours : {
       10:00 : 3,// count
       }
      },
      2021-05-04 : {
       count : 1, // count
       hours : null
      },
      2021-05-05 : {
       count : 1, // count
       hours : null
      },
}

1 个答案:

答案 0 :(得分:1)

只需使用 reduce() 将数组转换为所需的输出即可:

const array = [
  { date: '2021-04-28', hours: '05:30' },
  { date: '2021-04-28', hours: '05:30' },
  { date: '2021-04-28', hours: '03:00' },
  { date: '2021-04-20', hours: '10:00' },
  { date: '2021-04-20', hours: '10:00' },
  { date: '2021-04-20', hours: '10:00' },
  { date: '2021-05-04', hours: null },
  { date: '2021-05-05', hours: null }
];

const result = array.reduce((a, {date, hours}) => {
  a[date] = a[date] || {count: 0, hours: {}};
  a[date].count++;
  a[date].hours[hours] = a[date].hours[hours] || {count: 0};
  a[date].hours[hours].count++;
  
  return a;
}, {});

console.log(result);