Reputation: 111
how can convert serialized data from DOM to Object?
like :
const data = section.serialize();
const object = {data}
My current solution is:
const array = section.find('select, textarea, input').serializeArray();
var myObject = {};
$.map(array, (item, index) => {
myObject[item.name] = item.value;
});
this code convert to flat object but i hasn't any idea about inner array like:
obj = {
id: 1,
name : "ABC",
Persons:[] ???
}
Upvotes: 0
Views: 90
Reputation: 1314
To convert serialized data from the DOM to an object using jQuery, you can use the serializeArray() and then, you can convert that array into a JavaScript object using the reduce():
const section = $('#yourSectionId');
const dataArray = section.find('select, textarea, input').serializeArray();
const dataObject = dataArray.reduce(function (obj, item) {
obj[item.name] = item.value;
return obj;
}, {});
A compacter way, as alternative:
const section = $('#yourSectionId');
const dataObject = Object.fromEntries(section.find('select, textarea, input').serializeArray().map(({ name, value }) => [name, value]));
Upvotes: 0