Last active
July 21, 2023 19:05
-
-
Save rakeshpatra/ffcd1055204c8fa9b23faf075fb6f707 to your computer and use it in GitHub Desktop.
Transform nested object to formData
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Using lodash for _.forEach | |
function transformToFormData(data, formData=(new FormData), parentKey=null) { | |
_.forEach(data, (value, key) => { | |
if (value === null) return; // else "null" will be added | |
let formattedKey = _.isEmpty(parentKey) ? key : `${parentKey}[${key}]`; | |
if (value instanceof File) { | |
formData.set(formattedKey, value); | |
} else if (value instanceof Array){ | |
_.forEach(value, (ele) => {formData.append(`${formattedKey}[]`, ele)}); | |
} else if (value instanceof Object) { | |
transformToFormData(value, formData, formattedKey) | |
} else { | |
formData.set(formattedKey, value) | |
} | |
}) | |
return formData | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Suggestion: add before if statement to verify Object an statement for verify if value is Date
Reason: Date always is converted to null when considered Object
Now: