All files / objectToFormData objectToFormData.ts

60% Statements 15/25
42.85% Branches 9/21
50% Functions 1/2
58.33% Lines 14/24

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54                    1x         1x         1x 1x 1x 1x 1x 1x       1x 1x   1x   1x                       1x         1x    
/**
 * @description 对象递归转`FormData`,支持递归转换
 * @function objectToFormData
 * @param {Object} obj - 数据源对象
 * @returns {FormData} 转换后的数据,格式为FormData
 * @author liukun <919590347@qq.com>
 * @example
 * import { objectToFormData } from '@wont/utils'
 * objectToFormData({a:1})  // returns 1
 */
import { isNaN } from 'lodash-es'
 
interface NestedObj {
  [key: string]: NestedObj | string | number | File | File[] | any
}
export const objectToFormData = (
  obj: NestedObj,
  rawParentKey = '',
): FormData => {
  // console.log('obj :>> ', obj);
  const parentKey = rawParentKey
  const formData = new FormData()
  for (const key in obj) {
    if (Object.hasOwnProperty.call(obj, key)) {
      const value = obj[key]
      Iif ([undefined, null].includes(value) || isNaN(value)) {
        continue
      }
      // console.log('key,value :>> ', key, value);
      const propName = parentKey ? `${parentKey}[${key}]` : key
      Iif (value instanceof File) {
        formData.append(propName, value)
      } else Iif (typeof value === 'object' && !Array.isArray(value)) {
        objectToFormData(value, propName)
      } else Iif (Array.isArray(value)) {
        value.forEach((item) => {
          const arrayPropName = `${propName}`
          if (item instanceof File) {
            formData.append(arrayPropName, item)
          } else if (typeof item === 'object' && !Array.isArray(value)) {
            objectToFormData(item, arrayPropName)
          } else {
            formData.append(arrayPropName, item)
          }
        })
      } else {
        formData.append(propName, value.toString())
      }
    }
  }
  // console.log('formData :>> ', formData);
  return formData
}