I want convert an object to multiple objects in javascript.
this is my object:
const obj = jQuery('.sts_create form').serializeArray();
console.log
logs this:
1
:
{name: 'target_tag', value: 'a'}
2
:
{name: 'animation_status', value: 'animation-1'}
3
:
{name: 'duration', value: ''}
4
:
{name: 'target_tag', value: 'div'}
But I need it to be similar to this:
{
0 : {
target_tag:'',
animation_status:'',
duration:'',
},
1 : {
target_tag:'',
animation_status:'',
duration:'',
},
...
}
2
Answers
Does this help? Please see code comments for a bit of info on how this works.
EDIT: updated
collate
to expect an array rather than an object.Here’s a solution that self-serialises to an array of objects, you can then reformat that array in various different ways (included).
As there’s no HTML provided, the first assumption/change is that each "item" (group of fields) is itself each contained with another element – in this case:
this also allows for easy "user adds or deletes items to the form".
You can then loop through each wrapper to generate the field outputs and they are then self-contained, rather than a long, flat array that must be broken up.
View results in browser console (rather than snippet console)