How to serialize an Object into a list of URL query parameters?

Viewed 197067

Without knowing the keys of a JavaScript Object, how can I turn something like...

var obj = {
   param1: 'something',
   param2: 'somethingelse',
   param3: 'another'
}

obj[param4] = 'yetanother';

...into...

var str = 'param1=something&param2=somethingelse&param3=another&param4=yetanother';

...?

26 Answers

One line with no dependencies:

new URLSearchParams(obj).toString();
// OUT: param1=something&param2=somethingelse&param3=another&param4=yetanother

Use it with the URL builtin like so:

let obj = { param1: 'something', param2: 'somethingelse', param3: 'another' }
obj['param4'] = 'yetanother';
const url = new URL(`your_url.com`);
url.search = new URLSearchParams(obj);
const response = await fetch(url);

[Edit April 4, 2020]: null values will be interpreted as the string 'null'.

[Edit Mar 9, 2022]: browser compatibility

If you're using NodeJS 13.1 or superior you can use the native querystring module to parse query strings.

const qs = require('querystring');
let str = qs.stringify(obj)
Object.keys(obj).map(k => `${encodeURIComponent(k)}=${encodeURIComponent(obj[k])}`).join('&')

A useful code when you have the array in your query:

var queryString = Object.keys(query).map(key => {
    if (query[key].constructor === Array) {
        var theArrSerialized = ''
        for (let singleArrIndex of query[key]) {
            theArrSerialized = theArrSerialized + key + '[]=' + singleArrIndex + '&'
        }
        return theArrSerialized
    }
    else {
        return key + '=' + query[key] + '&'
    }
}
).join('');
console.log('?' + queryString)

This one-liner also handles nested objects and JSON.stringify them as needed:

let qs = Object.entries(obj).map(([k, v]) => `${k}=${encodeURIComponent(typeof (v) === "object" ? JSON.stringify(v) : v)}`).join('&')

A functional approach.

var kvToParam = R.mapObjIndexed((val, key) => {
  return '&' + key + '=' + encodeURIComponent(val);
});

var objToParams = R.compose(
  R.replace(/^&/, '?'),
  R.join(''),
  R.values,
  kvToParam
);

var o = {
  username: 'sloughfeg9',
  password: 'traveller'
};

console.log(objToParams(o));
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.22.1/ramda.min.js"></script>

I needed something that processes nested objects as well as arrays.

const Util = {
  isArray: function(val) {
    return Object.prototype.toString.call(val) === '[object Array]';
  },
  isNil: function(val) {
    return val === null || Util.typeOf(val)
  },
  typeOf: function(val, type) {
    return (type || 'undefined') === typeof val;
  },
  funEach: function(obj, fun) {
    if (Util.isNil(obj))
      return;      // empty value

    if (!Util.typeOf(obj, 'object'))
      obj = [obj]; // Convert to array

    if (Util.isArray(obj)) {
      // Iterate over array
      for (var i = 0, l = obj.length; i < l; i++)
        fun.call(null, obj[i], i, obj);
    } else {
      // Iterate over object
      for (var key in obj)
        Object.prototype.hasOwnProperty.call(obj, key) && fun.call(null, obj[key], key, obj);
    }
  }
};

const serialize = (params) => {
  let pair = [];

  const encodeValue = v => {
    if (Util.typeOf(v, 'object'))
      v = JSON.stringify(v);

    return encodeURIComponent(v);
  };

  Util.funEach(params, (val, key) => {
    let isNil = Util.isNil(val);

    if (!isNil && Util.isArray(val))
      key = `${key}[]`;
    else
      val = [val];

    Util.funEach(val, v => {
      pair.push(`${key}=${isNil ? "" : encodeValue(v)}`);
    });
  });

  return pair.join('&');
};

Usage:

serialize({
  id: null,
  lat: "27",
  lng: "53",
  polygon: ["27,53", "31,18", "22,62", "..."]
}); // "id=&lat=27&lng=53&polygon[]=27%2C53&polygon[]=31%2C18&polygon[]=22%2C62&polygon[]=..."

this method uses recursion to descend into object hierarchy and generate rails style params which rails interprets as embedded hashes. objToParams generates a query string with an extra ampersand on the end, and objToQuery removes the final amperseand.

 function objToQuery(obj){
  let str = objToParams(obj,'');
  return str.slice(0, str.length);
}
function   objToParams(obj, subobj){
  let str = "";

   for (let key in obj) {
     if(typeof(obj[key]) === 'object') {
       if(subobj){
         str += objToParams(obj[key], `${subobj}[${key}]`);
       } else {
         str += objToParams(obj[key], `[${key}]`);
       }

     } else {
       if(subobj){
         str += `${key}${subobj}=${obj[key]}&`;
       }else{
         str += `${key}=${obj[key]}&`;
       }
     }
   }
   return str;
 }

You could use npm lib query-string

const queryString = require('query-string');

querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' });
// Returns 'foo=bar&baz=qux&baz=quux&corge='

const obj = { id: 1, name: 'Neel' };
let str = '';
str = Object.entries(obj).map(([key, val]) => `${key}=${val}`).join('&');
console.log(str);

We should also handle the cases when the value of any entry is undefined, that key should not be included in the serialized string.

const serialize = (obj) => {
  return Object.entries(obj)
    .filter(([, value]) => value)
    .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
    .join('&');
}
export const convertObjToUrlParams = (obj) =>
{
    var paramString = '';
    for (let key in obj)
    {
        if (obj[key] !== null && obj[key] !== undefined)
        {
            paramString += '&';
            paramString += key + "=" + obj[key];
        }
    }
    return paramString;
}

Output Ex: &firstName=NoDo&userId=2acf67ed-73c7-4707-9b49-17e78afce42e&email=n@n.dk&phoneNumber=12345678&password=123456

try this... this is working for nested object also..

let my_obj = {'single':'this is single', 'nested':['child1','child2']};

((o)=>{ return Object.keys(o).map(function(key){ let ret=[]; if(Array.isArray(o[key])){ o[key].forEach((item)=>{ ret.push(`${key}[]=${encodeURIComponent(item)}`); }); }else{ ret.push(`${key}=${encodeURIComponent(o[key])}`); } return ret.join("&");  }).join("&"); })(my_obj);

With Axios and infinite depth:

<pre>
    <style>
      textarea {
        width: 80%;
        margin-bottom: 20px;
      }
      label {
        font-size: 18px;
        font-weight: bold;
      }
    </style>
    <label>URI</label>
    <textarea id="uri"  rows="7"></textarea>
    <label>All Defaults (Bonus): </label>
    <textarea id="defaults" rows="20"></textarea>
</pre>

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<script>
  const instance = axios.create({
    baseUrl: 'http://my-api-server',
    url: '/user'
  })
  const uri = instance.getUri({
    params: {
      id: '1234',
      favFruits: [
        'banana',
        'apple',
        'strawberry'
      ],
      carConfig: {
        items: ['keys', 'laptop'],
        type: 'sedan',
        other: {
          music: ['on', 'off', {
            foo: 'bar'
          }]
        }
      }
    }
  })
  const defaults = JSON.stringify(instance.defaults, null, 2)
  document.getElementById('uri').value = uri
  document.getElementById('defaults').value = defaults
</script>

Good Luck...

Related