therealparmesh / object-to-formdata

Convenient JavaScript function that serializes Objects to FormData instances.
MIT License
370 stars 62 forks source link

Can anyone suggest the reverse of its serializer #259

Open lekhnath opened 11 months ago

lekhnath commented 11 months ago

I need to convert form data back to JSON. But this library only support JSON to form data.

Thank you.

saidbenmoumen commented 4 months ago

made this to help me with that using lodash:

export function formDataToObj<T extends Record<string, any>>(
  formData: FormData
): T {
  const object = {} as T
  for (const [key, value] of formData.entries()) {
    // to handle allowEmptyArrays: true,
    if (key.endsWith('[]') && value === '') {
      set(object, key.slice(0, -2), [])
    } else set(object, key, value)
  }
  return object
}

with these options:

{
  indices: true,
  allowEmptyArrays: true,
}