Skip to content

Instantly share code, notes, and snippets.

@tjmehta
Last active October 31, 2024 23:25
Show Gist options
  • 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('');
}, '');
}
@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

@zm-rylee
Copy link

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

lol

That doesn't work with objects that contain arrays or other objects.

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