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
2 Answers
Reset to default 4To 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)