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

IT技术 javascript date reactjs ecmascript-6 momentjs
2021-05-25 03:16:27

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

数据列表看起来像这样,只有 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个回答
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

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