Skip to content

Instantly share code, notes, and snippets.

@rakeshpatra
Last active July 21, 2023 19:05
Show Gist options
  • Save rakeshpatra/ffcd1055204c8fa9b23faf075fb6f707 to your computer and use it in GitHub Desktop.
Save rakeshpatra/ffcd1055204c8fa9b23faf075fb6f707 to your computer and use it in GitHub Desktop.
Transform nested object to formData
// 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
}
@arthurdaszago
Copy link

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:

// 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 Date) {
      formData.set(formattedKey, value.toISOString())
    } 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