我怎样才能将我的JS对象转换为FormData?
我这样做的原因是,我有一个用~100个表单字段值构造的对象。
var item = {
description: 'Some Item',
price : '0.00',
srate : '0.00',
color : 'red',
...
...
}
现在我被要求将上传文件功能添加到我的表单,当然,通过JSON是不可能的,所以我计划移动到FormData。那么有什么方法可以将我的JS对象转换为FormData呢?
使用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());
使用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());
下面是一个使用Object.entries()的简单而甜蜜的解决方案,它甚至可以处理嵌套对象。
// If this is the object you want to convert to FormData...
const item = {
description: 'First item',
price: 13,
photo: File
};
const formData = new FormData();
Object.entries(item).forEach(([key, value]) => {
formData.append(key, value);
});
// At this point, you can then pass formData to your handler method
阅读更多关于Object.entries()在这里- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
很简单,可以这样做:
var item: { some1: "ajbd" , some2: "dds".. }
let myFormData = new FormData();
const abc = item.some1;
const xyz = item.some2;
myFormData.append('field1', abc);
myFormData.append('field2', xyz);
fetch('http:url', {
method: 'POST',
headers: {
'Content-Type': false,
},
body: myFormData,
}).
do promise ..