Reputation: 323
Can anyone please help me with formatting a date after a lodash _.filter? The below code results in "Tue Jan 21 2014 00:00:00 GMT-0500 (Eastern Standard Time)". I'd like the date to be in "m/d/yy" format.
var testdata=[{"date": "1/21/2014", "y": 325, "z": 201, "a": 85},
{"date": "1/22/2014", "y": 250, "z": null, "a": 40},
{"date": "1/23/2014", "y": 125, "z": 500, "a": 60},
{"date": "1/24/2014", "y": 50, "z": 466, "a": 35}
];
_.each(testdata, function(data){
var dateParts = data.date.split('/')
data.date = new Date(dateParts[2], dateParts[0] - 1, dateParts[1])
});
var startDate = new Date(start);
var endDate = new Date(end);
var requiredData = _.filter(testdata, function(data){
return data.date >= startDate && data.date <= endDate
});
Upvotes: 1
Views: 4133
Reputation: 7743
You need to _.map()
the _.filter()
'ed array to format your dates accordingly.
Change your last line to:
var requiredData = _.map(
_.filter(testdata, function(data){
return data.date >= startDate && data.date <= endDate
}), function(nextData){
return nextData.date.getDate() + '/' + (nextData.date.getMonth()+1) + '/' + nextData.date.getFullYear().toString().split('').slice(2,4).join('');
}
);
EDIT: I thought that you wanted only the formatted date. My bad. Change your requireData assignment to:
var requiredData = _.map(_.filter(testdata, function(data){
return data.date >= startDate && data.date <= endDate
} // end of _.filter()'s handler function
),
function(nextData){
// create new field called 'formatted' in each object with formatted date
nextData.formatted = (nextData.date.getMonth()+1) + '/' + nextData.date.getDate() + '/' + nextData.date.getFullYear().toString().split('').slice(2,4).join('');
return nextData;
} // end of _.map()'s handler function
);
This will make requiredData
an array of object as you had originally with the addition that each one will have a property formatted
that will hold the date in format m/d/yy
Upvotes: 2