Monday, June 30, 2014

Processing Form Data with jQuery and Lodash

I can get most of what I need for processing form data straight out of jQuery. I can listen for the submit event on the form, and I can prevent the form from actually getting submitted, allowing my own behaviour to run. jQuery also helps me collect the form data I need with the serializeArray() function. This function returns an array of form values. Lodash can help me transform this array into something more usable.

Here's an example that does exactly that. Rather than trying to manually map the array values into a form object, this approach builds a chain of Lodash functions that assembles the object we want.

$(function() {
    $( 'form' ).on( 'submit', function( e ) {
        e.preventDefault();

        var formData = $( e.currentTarget )
            .serializeArray();
        
        formData = _( formData )
            .groupBy( 'name' )
            .mapValues( function( i ) {
                return _( i )
                    .pluck( 'value' )
                    .first();
            })
            .value();
        
        console.log( formData );
    });
});

The formData variable is initialized with the serializeArray() data. However, before we actually start using formData, we want it setup as an object with the form input names as the keys — this is much easier to work with. We do so by calling the groupBy() function, which creates the object we're after. Each key is a form field. Next, we have to fix the values, because these still aren't quite right. They're still in the format returned by serializeArray() — we just need the actual form value. For this, we turn to mapValues(), which let's us assign the actual form field value to the key.

No comments :

Post a Comment