Skip to content

Instantly share code, notes, and snippets.

@jherax
Last active June 20, 2023 10:22
Show Gist options
  • Save jherax/7dd42406ebe2a2dc978c054f4f54c62e to your computer and use it in GitHub Desktop.
Save jherax/7dd42406ebe2a2dc978c054f4f54c62e to your computer and use it in GitHub Desktop.
Builds the url query parameters from an object
const isObject = (it) => it != null && typeof it === 'object';
/**
* Encodes an object to be used as query-string.
* It uses 'encodeURIComponent' to set each value.
*
* @param {object} data an object with key-value pairs to create the query-string
* @returns {string} the query-string
*/
function toUrlParams(data) {
let value;
if (!data) return '';
const serialized = [];
Object.keys(data).forEach((key) => {
value = data[key];
if (value === undefined) return; // continue;
if (typeof value === 'function') return;
if (isObject(value)) value = JSON.stringify(value);
// key and value should be decoded with decodeURIComponent
serialized.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
});
return `?${serialized.join('&')}`;
}
var data = {
SRC: 10,
gclid: "Cj0KEQjwnsPGBRDo4c6RqK",
subid: 102,
utm_medium: "cpc",
utm_source: "google",
utm_term: "market place",
};
var query = toUrlParams(data);
// expected:
// "?SRC=10&gclid=Cj0KEQjwnsPGBRDo4c6RqK&subid=102&utm_medium=cpc&utm_source=google&utm_term=market%20place"
/*
* If you want to pass an array, or an object to the url,
* they will be serialized as JSON and encoded with
* encodeURIComponent.
*/
data = {
id: 6716,
data: {
category: 'laptop',
brands: ['DELL', 'ASUS'],
},
};
query = toUrlParams(data);
// expected:
// "?id=6716&data=%7B%22category%22%3A%22laptop%22%2C%22brands%22%3A%5B%22DELL%22%2C%22ASUS%22%5D%7D"
/*
* Tip: You may use the function urlParamsToObject
* in order to convert the url parameters to an object.
* See: https://gist.github.com/jherax/e6ecb05aa35eb0219525
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment