generate dates and add new property to array of ob

2019-03-01 04:29发布

问题:

I have no control over a list of data, but I need to map it to a date range data.

The list of data look like this, which only have from and 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"
        }
    }
]

I'm able to generate a date range base on month

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');

How can I put the state object into the date range array like

[
{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

Or if you dont want to group:

  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

For explanation see other answer... Looks like theres a class out here isnt it? ;)