Skip to content

Instantly share code, notes, and snippets.

@TravelingTechGuy
Last active September 28, 2022 07:19
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save TravelingTechGuy/32454b95a50d296912b9 to your computer and use it in GitHub Desktop.
Save TravelingTechGuy/32454b95a50d296912b9 to your computer and use it in GitHub Desktop.
JSON object to query string (using underscore/lodash)
var objectToQueryString = function(obj) {
var qs = _.reduce(obj, function(result, value, key) {
return (!_.isNull(value) && !_.isUndefined(value)) ? (result += key + '=' + value + '&') : result;
}, '').slice(0, -1);
return qs;
};
@3ch01c
Copy link

3ch01c commented Apr 4, 2020

Here's some other options that don't require lodash.

'use strict'
// Other ways APIs implement URLSearchParams. Not my own, but I can't find the original source.
// https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/URLSearchParams

var obj = {
  a: 1,
  b: 2,
  c: [3, 4, 5, null, 7],
  foo: {bar: 'baz'}
};

function URLSearchParamsWithArrayBrackets(obj, prefix) {
  let str = [],
    p;
  for (p in obj) {
    if (obj.hasOwnProperty(p)) {
      let k = prefix ? prefix + "[]" : p,
        v = obj[p];
      str.push(
        v !== null && typeof v === "object"
          ? URLSearchParamsWithArrayBrackets(v, k)
          : encodeURIComponent(k) + "=" + encodeURIComponent(v)
      );
    }
  }
  return str.join("&");
}

function URLSearchParamsWithArrayIndices(obj, prefix) {
  let str = [],
    p;
  for (p in obj) {
    if (obj.hasOwnProperty(p)) {
      let k = prefix ? prefix + "[" + p + "]" : p,
        v = obj[p];
      str.push(
        v !== null && typeof v === "object"
          ? URLSearchParamsWithArrayIndices(v, k)
          : encodeURIComponent(k) + "=" + encodeURIComponent(v)
      );
    }
  }
  return str.join("&");
}

var params;
params = new URLSearchParams(obj).toString(); // 'a=1&b=2&c=3%2C4%2C5%2C%2C7&foo=%5Bobject+Object%5D'
params = URLSearchParamsWithArrayBrackets(obj); // 'a=1&b=2&c%5B%5D=3&c%5B%5D=4&c%5B%5D=5&c%5B%5D=null&c%5B%5D=7&foo%5B%5D=baz'
params = URLSearchParamsWithArrayIndices(obj); // 'a=1&b=2&c%5B0%5D=3&c%5B1%5D=4&c%5B2%5D=5&c%5B3%5D=null&c%5B4%5D=7&foo%5Bbar%5D=baz'

From https://gist.github.com/3ch01c/37b7a292c744628f189eeabc917a309b/

@giiska
Copy link

giiska commented Sep 28, 2022

Object.entries(someobject).reduce((result, item)=>{return result += ${item[0]}=${item[1]}&}, '').slice(0, -1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment