0

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:[] ???
}
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
rahman
  • 95
  • 8
  • https://stackoverflow.com/questions/1184624/convert-form-data-to-javascript-object-with-jquery – Alive to die - Anant Jun 29 '23 at 13:41
  • @freedomn-m no, when you use serializeArray if form has "multi Select input" it return list of same name like : {name: 'ID', value:'888'} {name: 'Persons', value: '11'} {name: 'Persons', value: '12'} {name: 'Persons', value: '13'} – rahman Jun 29 '23 at 15:15
  • 1
    Welcome to Stack Overflow. Please provide a [mcve]. – Twisty Jun 29 '23 at 18:42
  • Ok, so, still, can you provide an example HTML that you want to use to generate the output that you desire? See [mcve]. – freedomn-m Jun 30 '23 at 00:05

1 Answers1

0

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]));
sylvain
  • 853
  • 1
  • 7
  • 20