Handling duplicate query string arguments in Express.js

Duplicate query string entries are somewhat common, for example if you use Solr, you can do something like this:

/execute?facet.field=stream_size&facet.field=content_type

If you make an Express.js endpoint, you get can this data through the “query” option:

app.use('/execute/', 
  function(req, res) {
    console.log(req.query)
  }
)

The “req.query” is a Javascript object, which presents difficulties with duplicated arguments, which are joined into an array (so you do lose some information about order).

If, for example, you wanted to combine all back into a string, you could do it with something like this (assuming you use underscore/lodash):

let args = req.query;
 
let queryString =
  _.join(
    _.keys(args)
     .map( 
       (arg) => 
         isArray(args[arg]) ? 
         _.join(
           args[arg].map( 
             (argv) => arg + '=' + argv 
           ), 
         '&') : 
         arg + '=' + args[arg]), 
    '&');

Interested in JavaScript? I send out weekly, personalized emails with articles and conference talks. Click here to see an example and subscribe.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *