Skip to content

Instantly share code, notes, and snippets.

@Abdillah
Created March 18, 2019 05:50
Show Gist options
  • Select an option

  • Save Abdillah/87b584829522bbadcda201b3c03fe7a4 to your computer and use it in GitHub Desktop.

Select an option

Save Abdillah/87b584829522bbadcda201b3c03fe7a4 to your computer and use it in GitHub Desktop.
Nice to have independent functions
function objectToQueryStr(object) {
if (typeof object !== 'object') {
return '';
}
return Object.keys(object).reduce(function (acc, key) {
var item = key + '=' + encodeURI(object[key].toString());
if (acc.length) {
return acc + '&' + item;
}
return acc + item;
}, '');
}
function queryStrToObject(qs) {
if (!qs.length && typeof qs !== 'string') {
return {};
}
return qs.split('&').reduce(function (acc, item) {
var key = item.split('=', 2)[0];
var val = item.split('=', 2)[1] || item;
acc[key] = val;
return acc;
}, {});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment