Skip to content Skip to sidebar Skip to footer

Split From_date And To_date To A List Of Date Range Array

How can I transform from this array [ { 'date_from': '2017-05-06 00:00:00', 'date_to': '2017-05-08 23:59:59', 'event': 'code jam' }, {

Solution 1:

At first, iterate over the events, then loop over the events dates and store the events at these dates:

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

Then create an array out of that object ( and shorten the date) :

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:newDate(key*1000*60*60*24).format("dd-mm-yyyy"),events:output[key]});
}
console.log(arr);

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

Solution 2:

You can create new array using data from the previous array.

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 laststate:{
      name:'Some State'}
      })             

    });
    console.log(newData)

Solution 3:

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

Post a Comment for "Split From_date And To_date To A List Of Date Range Array"