在对象列表上使用 reduce 函数 javascript

using reduce function on list of objects javascript

我每周收到一些对象,这些对象上的每个对象都有日期、时间和其他字段。我想对这些对象数组每天的总小时数进行排序。

对象示例

var anArray = [{
  'End':"22:00",
  'Id':"Q45575",
  'Name':"W-299849",
  'Start':"20:00",
  'date':"2018-02-04",
  'hours':2
},{
  'End':"21:00",
  'Id':"Q45551",
  'Name':"W-299809",
  'Start':"15:00",
  'date':"2018-02-07",
  'hours':5
},{
  'End':"20:00",
  'Id':"Q45515",
  'Name':"W-299849",
  'Start':"10:00",
  'date':"2018-02-04",
  'hours':2
}];

输出应该是这样的,假设星期日是 2/4

周日周一周二周三周五周六

4 0 0 5 0 0

这就是我所拥有的

  var resourceData = data.reduce((a, c) => {
  var targetDay = new Date(c.date).getDay() === 6 ? 0 : (new Date(c.date).getDay() + 1);
  if (a) {
    a['week'][targetDay] += c.hours;
  } else {
    a = { 'week': new Array(7).fill(0) };
    a['week'][targetDay] = c.hours;
  }
  return a;
}, {});

无法正常工作,我收到 targetDay 错误

您的代码即将到达终点。

你可以让reduce的initialValue为{ 'week': new Array(7).fill(0) },不需要在reduce的处理程序中与if(a)比较。

查看下面代码中的注释:

var anArray = [{  'End':"22:00",  'Id':"Q45575",  'Name':"W-299849",  'Start':"20:00",  'date':"2018-02-04",  'hours':2},{  'End':"21:00",  'Id':"Q45551",  'Name':"W-299809",  'Start':"15:00",  'date':"2018-02-07",  'hours':5},{  'End':"20:00",  'Id':"Q45515",  'Name':"W-299849",  'Start':"10:00",  'date':"2018-02-04",  'hours':2}];

var resourceData = anArray.reduce((a, c) => {
  var targetDay = new Date(c.date).getDay() === 6 ? 0 : (new Date(c.date).getDay() + 1);
  a['week'][targetDay] += c.hours;

  /*
  else {
    a = { 'week': new Array(7).fill(0) };
    a['week'][targetDay] = c.hours;
  }*/ //remove else block because already created [var a] by the initialValue
  return a;
}, { 'week': new Array(7).fill(0) }); //initialize with expected object instead of {}

console.log(resourceData)

而不是减少,为此我认为 forEach 似乎更合适。

示例如下。

var anArray = [{
  'End':"22:00",
  'Id':"Q45575",
  'Name':"W-299849",
  'Start':"20:00",
  'date':"2018-02-04",
  'hours':2
},{
  'End':"21:00",
  'Id':"Q45551",
  'Name':"W-299809",
  'Start':"15:00",
  'date':"2018-02-07",
  'hours':5
},{
  'End':"20:00",
  'Id':"Q45515",
  'Name':"W-299849",
  'Start':"10:00",
  'date':"2018-02-04",
  'hours':2
}];

var days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];

var result = {};

//lets just zero every day
(new Array(7).fill(0)).map((x,ix) => { 
  result[days[ix]] = 0;
});

//now lets add them up
anArray.forEach((d) => {
  var dt = new Date(d.date);
  result[days[dt.getDay()]] += d.hours;
});

console.log(result);