Modelesq Modelesq - 6 months ago 8
Javascript Question

Loop through form inputs and store data in object

I'm just trying to create a javascript object.

const data = {};

// loop through each input found in form
$('#form_name').filter(':input').each(function() {
const $id = $(this).attr('id');
const $value = $(this).attr('value');
data[$id] = $value;
return data;
});


Checkout this fiddle to show you what I mean... https://jsfiddle.net/atg5m6ym/5230/

Expected output would be something like this:

{
"username": "johndoe",
"email": "johndoe@gmail.com",
...
}


This way currently does not work... How can I make this into a js object or if someone could offer a better way of doing this, that would be great. Thank you for your help in advance!

Ben Ben
Answer

You should not return data object in the each loop, but after:

var setData = function(){
   var data = {};

   $('#form_name').filter(':input').each(function() {
       const $id = $(this).attr('id');
       const $value = $(this).attr('value');
       data[$id] = $value;
   });

   return data;
}

var data = setObject();

also, you should not define your object as a constant since you change its value right after