Convert Js Object to Form Data

Convert JS Object to form data

If you have an object, you can easily create a FormData object and append the names and values from that object to formData.

You haven't posted any code, so it's a general example;

var form_data = new FormData();

for ( var key in item ) {
form_data.append(key, item[key]);
}

$.ajax({
url : 'http://example.com/upload.php',
data : form_data,
processData : false,
contentType : false,
type: 'POST'
}).done(function(data){
// do stuff
});

There are more examples in the documentation on MDN

Convert form data to JavaScript object with jQuery

serializeArray already does exactly that. You just need to massage the data into your required format:

function objectifyForm(formArray) {
//serialize data function
var returnArray = {};
for (var i = 0; i < formArray.length; i++){
returnArray[formArray[i]['name']] = formArray[i]['value'];
}
return returnArray;
}

Watch out for hidden fields which have the same name as real inputs as they will get overwritten.

how to convert JSON into multipart/form-data

Something like this:

let form_data = new FormData();

form_data.set('data', {
"image": this.state.file,
"title" : this.state.title,
"description": this.state.description,
});

ax({
url: '/api',
method: 'post',
data: form_data,
headers: {'content-type': 'multipart/form-data'}
})
.then(response => {
})
.catch(error => {
});

Converting form data to JSON

I've never used jquery, nevertheless googling and with personal knowledge i came up with this.

 $(function () {
$('#frmSearch').submit(function (event) {
event.preventDefault();
object= {}
formData = new FormData(event.target);
formData.forEach((value, key) => object[key] = value);
alert('got here');
var txt = JSON.stringify(object);
alert(txt)
})
});

I hope i have been able to help you! Regards.

How to convert FormData (HTML5 object) to JSON

You could also use forEach on the FormData object directly:

var object = {};
formData.forEach(function(value, key){
object[key] = value;
});
var json = JSON.stringify(object);


UPDATE:

And for those who prefer the same solution with ES6 arrow functions:

var object = {};
formData.forEach((value, key) => object[key] = value);
var json = JSON.stringify(object);

UPDATE 2:

And for those who want support for multi select lists or other form elements with multiple values (since there are so many comments below the answer regarding this issue I will add a possible solution):

var object = {};
formData.forEach((value, key) => {
// Reflect.has in favor of: object.hasOwnProperty(key)
if(!Reflect.has(object, key)){
object[key] = value;
return;
}
if(!Array.isArray(object[key])){
object[key] = [object[key]];
}
object[key].push(value);
});
var json = JSON.stringify(object);

Here a Fiddle demonstrating the use of this method with a simple multi select list.

UPDATE 3:

As a side note for those ending up here, in case the purpose of converting the form data to json is to send it through a XML HTTP request to a server you can send the FormData object directly without converting it. As simple as this:

var request = new XMLHttpRequest();
request.open("POST", "http://example.com/submitform.php");
request.send(formData);

See also Using FormData Objects on MDN for reference:

UPDATE 4:

As mentioned in one of the comments below my answer the JSON stringify method won't work out of the box for all types of objects. For more information on what types are supported I would like to refer to the Description section in the MDN documentation of JSON.stringify.

In the description is also mentioned that:

If the value has a toJSON() method, it's responsible to define what data will be serialized.

This means that you can supply your own toJSON serialization method with logic for serializing your custom objects. Like that you can quickly and easily build serialization support for more complex object trees.

Convert formData with nested keys to JS Object

You could use something like lodash's _.set function, or else an implementation of the same feature in vanilla JavaScript, which I will use in below snippet:

// This function is taken from https://stackoverflow.com/a/54733755/5459839
function deepSet(obj, path, value) {
if (Object(obj) !== obj) return obj; // When obj is not an object
// If not yet an array, get the keys from the string-path
if (!Array.isArray(path)) path = path.toString().match(/[^.[\]]+/g) || [];
path.slice(0,-1).reduce((a, c, i) => // Iterate all of them except the last one
Object(a[c]) === a[c] // Does the key exist and is its value an object?
// Yes: then follow that path
? a[c]
// No: create the key. Is the next key a potential array-index?
: a[c] = Math.abs(path[i+1])>>0 === +path[i+1]
? [] // Yes: assign a new array object
: {}, // No: assign a new plain object
obj)[path[path.length-1]] = value; // Finally assign the value to the last key
return obj; // Return the top-level object to allow chaining
}

// Use it for formData:
function formDataObject(form) {
const formData = new FormData(form);
const root = {};
for (const [path, value] of formData) {
deepSet(root, path, value);
}
return root;
}

// Example run
const result = formDataObject(document.forms[0]);
console.log(result);
<form>
<input name="item[0][id]" value="0121"/>
<input name="item[0][name]" value="Birmingham"/>
<input name="item[1][id]" value="01675"/>
<input name="item[1][name]" value="Warwickshire"/>
</form>


Related Topics



Leave a reply



Submit