Skip to content

Instantly share code, notes, and snippets.

@IgorFachini
Last active May 1, 2022 19:50
Show Gist options
  • Save IgorFachini/03d93c14bf42c7d31a6b685a2381d8fc to your computer and use it in GitHub Desktop.
Save IgorFachini/03d93c14bf42c7d31a6b685a2381d8fc to your computer and use it in GitHub Desktop.
JavaScript: Convert data by field name contains Date to data Date object, suports objects, arrays recursivelly.
/**
* Convert data by field name contains Date to data Date object
* @param {Array, Object, String} date
* @param {String} fieldName
* @returns {Array, Object, String, Boolean, null}
*/
const covertDateFieldName = (data, fieldName) => {
if (Array.isArray(data)) return data.map(d => covertDateFieldName(d))
if (typeof data === 'object') {
for (const key in data) {
data[key] = covertDateFieldName(data[key], key)
}
}
if (typeof fieldName === 'string' && fieldName.includes('Date')) return new Date(data)
return data
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment