我怎样才能将我的JS对象转换为FormData?

我这样做的原因是,我有一个用~100个表单字段值构造的对象。

var item = {
   description: 'Some Item',
   price : '0.00',
   srate : '0.00',
   color : 'red',
   ...
   ...
}

现在我被要求将上传文件功能添加到我的表单,当然,通过JSON是不可能的,所以我计划移动到FormData。那么有什么方法可以将我的JS对象转换为FormData呢?


当前回答

尝试 obj2fd=> https://www.npmjs.com/package/obj2fd

import obj2fd from 'obj2fd'

let data = {a:1, b:2, c:{ca:1}};
let dataWithFormData = obj2fd(data);
//result => [a=>1, b=>2, c=>[ca=>1]]

其他回答

递归地

const toFormData = (f => f(f))(h => f => f(x => h(h)(f)(x)))(f => fd => pk => d => { if (d instanceof Object) { Object.keys(d).forEach(k => { const v = d[k] if (pk) k = `${pk}[${k}]` if (v instanceof Object && !(v instanceof Date) && !(v instanceof File)) { return f(fd)(k)(v) } else { fd.append(k, v) } }) } return fd })(new FormData())() let data = { name: 'John', age: 30, colors: ['red', 'green', 'blue'], children: [ { name: 'Max', age: 3 }, { name: 'Madonna', age: 10 } ] } console.log('data', data) document.getElementById("data").insertAdjacentHTML('beforeend', JSON.stringify(data)) let formData = toFormData(data) for (let key of formData.keys()) { console.log(key, formData.getAll(key).join(',')) document.getElementById("item").insertAdjacentHTML('beforeend', `<li>${key} = ${formData.getAll(key).join(',')}</li>`) } <p id="data"></p> <ul id="item"></ul>

尝试JSON。函数如下所示

var postData = JSON.stringify(item);
var formData = new FormData();
formData.append("postData",postData );

我可能有点晚了,但这就是我创建的将单个对象转换为FormData的方法。

function formData(formData, filesIgnore = []) {
  let data = new FormData();

  let files = filesIgnore;

  Object.entries(formData).forEach(([key, value]) => {
    if (typeof value === 'object' && !files.includes(key)) {
      data.append(key, JSON.stringify(value) || null);
    } else if (files.includes(key)) {
      data.append(key, value[0] || null);
    } else {
      data.append(key, value || null);
    }
  })

  return data;
}

它是如何工作的? 它将转换并返回所有属性,除了您在忽略列表中设置的File对象(第二个参数)。如果有人能告诉我一个更好的方法来确定这将有帮助!)变成一个json字符串使用json .stringify。然后在您的服务器上,您只需要将其转换回JSON对象。

例子:

let form = {
  first_name: 'John',
  last_name: 'Doe',
  details: {
    phone_number: 1234 5678 910,
    address: '123 Some Street',
  },
  profile_picture: [object FileList] // set by your form file input. Currently only support 1 file per property.
}

function submit() {
  let data = formData(form, ['profile_picture']);

  axios.post('/url', data).then(res => {
    console.log('object uploaded');
  })
}

我仍然有点新的Http请求和JavaScript,所以任何反馈将高度赞赏!

使用ES6和更函数式的编程方法@adeneo的答案可能是这样的:

function getFormData(object) {
    const formData = new FormData();
    Object.keys(object).forEach(key => formData.append(key, object[key]));
    return formData;
}

或者使用.reduce()和箭头函数:

const getFormData = object => Object.keys(object).reduce((formData, key) => {
    formData.append(key, object[key]);
    return formData;
}, new FormData());

你可以简单地安装qs:

npm i qs

简单的导入:

import qs from 'qs'

将对象传递给qs.stringify():

var item = {
   description: 'Some Item',
   price : '0.00',
   srate : '0.00',
   color : 'red',
   ...
   ...
}

qs.stringify(item)