最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I can convert my JS Object to FormData? - Stack Overflow

programmeradmin2浏览0评论

How can I define object in object in FormData?

for example:

var item = {
   description: 'kavan ahmadi',
   price : '0.00',
   item1:{ firtname:'k1', file:'file'},
   count:'1'
}

How can I define object in object in FormData?

for example:

var item = {
   description: 'kavan ahmadi',
   price : '0.00',
   item1:{ firtname:'k1', file:'file'},
   count:'1'
}
Share Improve this question asked Mar 13, 2021 at 8:27 Kavan AhmadiKavan Ahmadi 411 gold badge1 silver badge5 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

To define the object in form data, you need to append each object property and value into formData.

Just append the key and its value into formData.

Here is the ES6 approach:

function getFormData(object) {
    const formData = new FormData();
    Object.keys(object).forEach(key => {
      if (typeof object[key] !== 'object') formData.append(key, object[key])
      else formData.append(key, JSON.stringify(object[key]))
    })
    return formData;
}

Just pass your object into the getFormData function, and it will do the rest.

Check with your code example: https://jsbin./lurocexoxi/edit?js,console,output

You cannot pass non-primitive values (eg objects, arrays) as values to formData.append. Your choices, then, are to use dot-syntax in your keys:

formData.append('item1.firstName', 'Jimminey');
formData.append('item1.lastName', 'Cricket');

Or stringify the object;

formData.append('item1', '{ "firstName": "Jimminey", "lastName": "Cricket" }');

Here's an example, with non-primitive values converted to JSON strings:

let formData = new FormData();

// Loop through the object
for (let [key, val] of Object.entries(item)) {
  // append each item to the formData (converted to JSON strings)
  formData.append(key, JSON.stringify(val));
}

If you want to send plex data in a network request, you're better off sending it as application/json (JSON document), instead of multipart/form-data (FormData)

发布评论

评论列表(0)

  1. 暂无评论