I have some html objects like:
<input id="myfield1" class="fields_to_iterate">
<input id="myfield2" class="fields_to_iterate">
<input id="myfield3" class="fields_to_iterate">
<input id="myfield4" class="fields_to_iterate">
<input id="myfield5" class="fields_to_iterate">
and if I do in javascript:
$('.fields_to_iterate').each( (index, element) => {
myObject.push( { [$(element).attr('id')] : $(element).val() } );
});
On console.log debug get as result an object like this:
transferBook: Array(7)
0 : {myfield1: 'value1'}
1 : {myfield2: 'value2'}
2 : {myfield3: 'value3'}
3 : {myfield4: 'value4'}
4 : {myfield5: 'value5'}
length: 5
[[Prototype]] : Array(0)
but I’d like to get only one array like:
transferBook: Array(1)
0 : {myfield1: 'value1', myfield2: 'value2', myfield3: 'value3', myfield4: 'value4', myfield5: 'value5'}
length: 1
[[Prototype]] : Array(0)
How I could modify my .each() to push in single array? Thanks to all! Cheers!
4
Answers
It seems like you want to create an object of key value pairs for each input’s
id
andvalue
.If you need solution based on JQuery Use
reduce
insteadeach
like this:Who needs jQuery?
See
If you really want it in an array, simply wrap it in square brackets
You can use jQuery’s
map
instead, andObject.fromEntries
to create an object from an array of key-value pairs.