Reputation: 12923
So consider the following object:
You might be thinking, the easiest way is too loop over the object, check if each property is valid. as you can see we have one date object in this object. But pay attention to that clinic_id
.
Here's my code to do what I mentioned above:
for(let property in formData) {
let date = moment(formData[property]).isValid()
if (date) {
formData[property] = moment(formData[property]).format('YYYY-MM-DD');
}
}
You would think this might work, heck you might even suggest to loop through looking to see what .getDate()
on each property would say, except .getDate()
will throw an error on anything not a date object.
So what does the code above output:
The only thing in here that should be a date value is date_of_consent
not clinic_id
. I understand why moment converted it to a date but it should not have happened.
I will have objects that have date objects in them, is there a way for me to find said date object in an object and replace it with a moment.js
formatted one?
Upvotes: 1
Views: 1292
Reputation: 1545
You can check if you have Date
objects in multiple ways.
You could check the instance of every item to check if it's a Date :
if (formData[property] instanceof Date) // returns true or false
You could also check if the function .getDate()
exists :
typeof (formData[property]).getDate === 'function'
Or try to get the value and catch the possible error :
try {
var date = formData[property].getDate();
/* Do your formatting */
} catch (e) {
//This was not a Date object
}
Upvotes: 1