Skip to content

Instantly share code, notes, and snippets.

@tjmehta
Last active January 28, 2024 22:35
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save tjmehta/9204891 to your computer and use it in GitHub Desktop.
Save tjmehta/9204891 to your computer and use it in GitHub Desktop.
Object to Querystring - JavaScript, JS, JSON
function objectToQuerystring (obj) {
return Object.keys.reduce(function (str, key, i) {
var delimiter, val;
delimiter = (i === 0) ? '?' : '&';
key = encodeURIComponent(key);
val = encodeURIComponent(obj[key]);
return [str, delimiter, key, '=', val].join('');
}, '');
}
@dejurin
Copy link

dejurin commented Aug 18, 2017

thank u

@lingqingmeng
Copy link

Should be

function objectToQuerystring (obj) {
  return Object.keys(obj).reduce(function (str, key, i) {
    var delimiter, val;
    delimiter = (i === 0) ? '?' : '&';
    key = encodeURIComponent(key);
    val = encodeURIComponent(obj[key]);
    return [str, delimiter, key, '=', val].join('');
  }, '');
}

@rezaamya
Copy link

It wont work on nested Object like this one:
var data = {
"_id": "5973782bdb9a930533b05cb2",
"isActive": true,
"balance": "$1,446.35",
"age": 32,
"name": "Logan Keller",
"email": "logankeller@artiq.com",
"phone": "+1 (952) 533-2258",
"friends": [{
"id": 0,
"name": "Colon Salazar"
},
{
"id": 1,
"name": "French Mcneil"
},
{
"id": 2,
"name": "Carol Martin"
}
],
"favoriteFruit": "banana"
};

@marcelo-ribeiro
Copy link

const serialize = obj => Object.keys(obj).map(key => encodeURIComponent(key) + '=' + encodeURIComponent(obj[key])).join('&');

@felipemarques
Copy link

felipemarques commented Jul 20, 2018

function objectToQuerystring (obj) {
  return Object.keys(obj).reduce(function (str, key, i) {
    var delimiter, val;
    delimiter = (i === 0) ? '?' : '&';
    key = encodeURIComponent(key);
    val = encodeURIComponent(obj[key]);
    return [str, delimiter, key, '=', val].join('');
  }, '');
}

@gerardcarbo
Copy link

With array support:

function objectToQuerystring (obj) {
  return Object.keys(obj).filter((key) => obj[key] != undefined && obj[key] != '').reduce((str, key, i) => {
    var delimiter: string, val;
    delimiter = (i === 0) ? '?' : '&';
    if(Array.isArray(obj[key])) {
      key = encodeURIComponent(key);
      var arrayVar = obj[key].reduce((str, item) => {
        val = encodeURIComponent(JSON.stringify(item));
        return [str, key, '=', val, '&'].join(''); 
      }, '');
      return [str, delimiter, arrayVar.trimRightString('&')].join('');
    } else {
      key = encodeURIComponent(key);
      val = encodeURIComponent(JSON.stringify(obj[key]));
      return [str, delimiter, key, '=', val].join('');      
    }
  }, '');

@bumi001
Copy link

bumi001 commented Oct 15, 2018

  key = encodeURIComponent(key);
  var arrayVar = obj[key].reduce((str, item) => {

After the assignment key = encodeURIComponent(key), obj[key] in the second line may not work as intended. Here is an improved version:

const objectToQuerystring = (obj) => {
const sp = new URLSearchParams();
Object.keys(obj).filter((key) => obj[key] != undefined && obj[key] != '').forEach(key => {
const ekey = encodeURIComponent(key);
if(Array.isArray(obj[key])) {
obj[key].forEach(val => {
sp.append(ekey, encodeURIComponent(JSON.stringify(val)));
});
} else {
sp.append(ekey, encodeURIComponent(JSON.stringify(obj[key])));
}
});
return "?"+sp.toString();
}

@zymr-keshav
Copy link

this check for object/string/boolean/string

 serialize(params: any) {
        const result = [];
        if (Object.keys(params).length > 0) {
            for (const key in params) {
                if (params.hasOwnProperty(key)) {
                    const keyValue = params[key];
                    if (keyValue !== null) {
                        switch (keyValue.constructor.name) {
                            case 'Array':
                                if (keyValue.length > 0) {
                                    const joined_value = keyValue.join(',');
                                    result.push(`${encodeURIComponent(key)}=${encodeURIComponent(joined_value)}`);
                                }
                                break;
                            case 'Object':
                                (<any>Object).entries(keyValue).map(([k, v]: [string, any]) => {
                                    if (v) {
                                        result.push(`${encodeURIComponent(k)}=${encodeURIComponent(v)}`);
                                    }
                                });
                                break;
                            default:
                                result.push(`${encodeURIComponent(key)}=${encodeURIComponent(keyValue)}`);
                        }
                    }
                }
            }
            return result.join('&');
        } else {
            return result;
        }
    }

@tylik1
Copy link

tylik1 commented Mar 29, 2019

@gerardcarbo you have 3 mistakes in your function

  1. var delimiter: string, val; => var delimiter, string, val;
  2. There is no trimRightString but trimRight is correct
  3. You forgot closing } at the end

Also array values in query string should be handled like this: ?arg[]=1&arg[]=2

@sagarpanchal
Copy link

export const toQueryString = object =>
  '?' +
  Object.keys(object)
    .map(key => `${key}=${object[key].toString()}`)
    .join('&');

@darkylmnx
Copy link

So handle recursive objects or arrays in the STANDARD query form a=val&b[0]=val&b[1]=val&c=val&d[some key]=val, here's the final function.

  • It skips values for functions, null, undefined
  • It skips keys and values for empty objects and arrays.
  • It doesn't handle Number or String Objects made with new Number(1) or new String('my string') because NO ONE should ever do that
const objectToQueryString = (initialObj) => {
    const reducer = (obj, parentPrefix = null) => (prev, key) => {
      const val = obj[key];
      key = encodeURIComponent(key);
      const prefix = parentPrefix ? `${parentPrefix}[${key}]` : key;

      if (val == null || typeof val === 'function') {
        prev.push(`${prefix}=`);
        return prev;
      }

      if (['number', 'boolean', 'string'].includes(typeof val)) {
        prev.push(`${prefix}=${encodeURIComponent(val)}`);
        return prev;
      }

      prev.push(Object.keys(val).reduce(reducer(val, prefix), []).join('&'));
      return prev;
    };

    return Object.keys(initialObj).reduce(reducer(initialObj), []).join('&');
  };

  objectToQueryString({
    name: 'John Doe',
    age: 20,
    children: [
      { name: 'Foo Doe' },
      { name: 'Bar Doe' }
    ],
    wife: {
      name: 'Jane Doe'
    }
  });
  // -> name=John%20Doe&age=20&children[0][name]=Foo%20Doe&children[1][name]=Bar%20Doe&wife[name]=Jane%20Doe

@bhaireshm
Copy link

bhaireshm commented Jul 12, 2021

const objectToQueryParams = (o = {}) => Object.entries(o) .map((p) => `${encodeURIComponent(p[0])}=${encodeURIComponent(p[1])}`) .join("&");

Refer below gist for more:
https://gist.github.com/bhaireshm

@chjlsch
Copy link

chjlsch commented Jan 6, 2022

i created a gist for to recursively encode and decode querystrings (encode = object to querystring, decode = querystring to object).
Feel free to copy/paste this in your own projects.

Thanks @darkylmnx (his answer) for your encode function. I added the corresponding decode function (both in typescript format).
I tested the code by creating an complex object, encoding it to a querystring and decoding it to an object, then i compared the input object with the decoded output object.

@imdavmena
Copy link

Great 🔥 💯

@aslan0402
Copy link

const objectToQuerystring = obj => new URLSearchParams(obj).toString();

lol

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