Search code examples
javascriptlodash

How can I create a URL encoded query string from an array of objects?


I found tons of examples of how to turn an objects keys/values into a URL encoded query string, but I need to use an array of objects and turn them into a query string.

I want to use pure JS or lodash to accomplish this task.

I am supplying an array of objects in this format:

[
  { points: "30.09404881287048,-96.064453125" },
  { points: "30.09404881287048,-94.63485717773439" },
  { points: "29.345072482286373,-96.064453125" },
  { points: "29.345072482286373,-94.63485717773439"}
]

I need it to be in this format:

points=30.09404881287048%2C-96.064453125&points=30.09404881287048%2C-94.63485717773439&points=29.345072482286373%2C-96.064453125&points=29.345072482286373%2C-94.63485717773439

I am currently accomplishing this using these two methods:

import { map as _map } from 'lodash';

const createQueryStringFromObject = object =>
  _map(object, (value, key) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
    .join('&');

const createQueryStringFromArray = array => array.reduce((queryString, object, index) => {
  return queryString + createQueryStringFromObject(object) + (index < array.length - 1 ? '&' : '');
}, '');

I find the reduce function implementation sloppy though and I think it could be cleaner and more efficient. Any suggestions?

EDIT: I would like to keep the method generic so it can accept an array of objects with any key and not just specifically the key points. I also would like to keep the createQueryStringFromObject() method because I need it elsewhere on the site.


Solution

  • I am looking for a generic implementation that is not specific to any objects containing the key of points. Thanks to melpomene's suggestion to just use another map and join, I gave that a shot and I definitely like that format alot more. Much shorter and clear!

    const createQueryStringFromArray = array =>
      _map(array, object => createQueryStringFromObject(object))
        .join('&');