Convert JS Object to form data

前端 未结 18 1884
孤街浪徒
孤街浪徒 2020-11-29 17:22

How can I can convert my JS Object to FormData?

The reason why I want to do this is, I have an object that I constructed out of the ~100 form field valu

18条回答
  •  执念已碎
    2020-11-29 17:31

    In my case my object also had property which was array of files. Since they are binary they should be dealt differently - index doesn't need to be part of the key. So i modified @Vladimir Novopashin's and @developer033's answer:

    export function convertToFormData(data, formData, parentKey) {
      if(data === null || data === undefined) return null;
    
      formData = formData || new FormData();
    
      if (typeof data === 'object' && !(data instanceof Date) && !(data instanceof File)) {
        Object.keys(data).forEach(key => 
          convertToFormData(data[key], formData, (!parentKey ? key : (data[key] instanceof File ? parentKey : `${parentKey}[${key}]`)))
        );
      } else {
        formData.append(parentKey, data);
      }
    
      return formData;
    }
    

提交回复
热议问题