生成日期并将新属性添加到对象数组

时间:2017-05-07 11:22:50

标签: javascript date reactjs ecmascript-6 momentjs

我无法控制数据列表,但我需要将其映射到日期范围数据。

数据列表看起来像这样,只有from和to。

[
    {
        "date_from": "2017-05-06 00:00:00",
        "date_to": "2017-05-08 23:59:59",
        "state": {
            "name": "San francisco"
        }
    }
    {
        "date_from": "2017-05-03 00:00:00",
        "date_to": "2017-05-07 23:59:59",
        "state": {
            "name": "Las Vegas"
        }
    }
]

我能够根据月份生成日期范围

function generateDates(startDate, stopDate) {
  var dateArray = [];
  var currentDate = moment(startDate);
  var stopDate = moment(stopDate);
  while (currentDate <= stopDate) {
    dateArray.push({
      date: moment(currentDate).format('YYYY-MM-DD')
    });
    currentDate = moment(currentDate).add(1, 'days');
  }

  return dateArray;
}

generateDates('2017-05-01', '2017-05-31');

如何将状态对象放入日期范围数组中,如

[
{date: '2017-05-06', state:{name:'San francisco'}},
{date: '2017-05-07', state:{name:'San francisco'}},
{date: '2017-05-08', state:{name:'San francisco'}},
..
..
]

1 个答案:

答案 0 :(得分:-1)

var sparse=input.reduce((sparse,event)=>generateDates(event.date_from,event.date_to).forEach(date=>(sparse[date]=sparse[date]||[]).push(event))||sparse,{});

var result=[];
for(date in sparse){
 result.push({date:date,states:sparse[date].map(el=>el.state)});
}

http://jsbin.com/larumiyeli/edit?console

或者如果你不想分组:

  var result=input.reduce((sparse,event)=>sparse.concat(generateDates(event.date_from,event.date_to).map(el=>(el.state=event.state,el)),[]);

http://jsbin.com/mixorecoyo/edit?console

有关解释,请参阅其他答案......看起来这里的课程不是吗? ;)