Split from_date and to_date into a list of date range arrays
How can I convert from this array
[
{
"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"
}
]
to that?
[
..
..
{date: '2017-05-06', state:{name:'San francisco'}},
{date: '2017-05-07', state:{name:'San francisco'}},
{date: '2017-05-08', state:{name:'San francisco'}},
..
..
]
I don't know where to start. I am provided with an API where I cannot change its structure, I need the data to be in a list of date ranges so that I can match against the calendar plugin. Help is needed.
+3
source to share
3 answers
First go by events, then collapse the event dates and store events to those dates:
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;
},{});
Then create an array from 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:new Date(key*1000*60*60*24).format("dd-mm-yyyy"),events:output[key]});
}
console.log(arr);
+2
source to share
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);
+1
source to share
You can create a 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 last
state:{
name:'Some State'}
})
});
console.log(newData)
0
source to share