将from_date和to_date拆分为日期范围数组列表

时间:2017-05-07 13:15:45

标签: javascript reactjs ecmascript-6 momentjs

如何从此数组转换

[
    {
        "date_from": "2017-05-06 00:00:00",
        "date_to": "2017-05-08 23:59:59",
        "event": "code jam"
    },
    {
        "date_from": "2017-05-03 00:00:00",
        "date_to": "2017-05-07 23:59:59",
        "event": "boxing day"
    }
]

到此?

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

我不知道从哪里开始。我给了一个我无法更改结构的API,我需要将数据放在日期范围列表中,以便我可以使用日历插件进行映射。需要帮忙。

3 个答案:

答案 0 :(得分:2)

首先,迭代事件,然后循环事件日期并在这些日期存储事件:

var output=input.reduce(function(obj,event){
   for(var day=Math.floor(+new Date(event.date_from)/(1000*60*60*24)+1),max=Math.floor(+new Date(event.date_to)/(1000*60*60*24));day<=max;day++){
       (obj[day]=obj[day]||[]).push(event);
   }
 return obj;
},{});

然后从该对象中创建一个数组(并缩短日期):

Date.prototype.format=function(str){
var map={
  dd:this.getDate(),
  mm:this.getMonth()+1,
  yyyy:this.getFullYear()
}
return str.split("-").map(el=>map[el]||"00").join("-");
}


var arr=[];
for(key in output){
  arr.push({date:new Date(key*1000*60*60*24).format("dd-mm-yyyy"),events:output[key]});
}
console.log(arr);

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

答案 1 :(得分:1)

var data = [
    {
        "date_from": "2017-05-06 00:00:00",
        "date_to": "2017-05-08 23:59:59",
        "event": "code jam"
    },
    {
        "date_from": "2017-05-03 00:00:00",
        "date_to": "2017-05-07 23:59:59",
        "event": "boxing day"
    }
];

var transformedData = data
  .map(datum => [{date: datum.date_from.substr(0, 10)}, {date: datum.date_to.substr(0, 10)}])
  .reduce((allItems, items) => allItems.concat(items), [])
  .map(item => ({date: item.date, state: {name:'San francisco'}}));

console.log(transformedData);

答案 2 :(得分:0)

您可以使用上一个数组中的数据创建新数组。

&#13;
&#13;
 var data = [{
        "date_from": "2017-05-06 00:00:00",
        "date_to": "2017-05-08 23:59:59",
        "event": "code jam"
      },
      {
        "date_from": "2017-05-03 00:00:00",
        "date_to": "2017-05-07 23:59:59",
        "event": "boxing day"
      }
    ];

    var newData =[]
    data.forEach(function(item){
      newData.push({
      date:item['date_from'].slice(0, -9), // removing characters from last
      state:{
      name:'Some State'}
      })             

    });
    console.log(newData)
&#13;
&#13;
&#13;