Skip to content

Instantly share code, notes, and snippets.

@kevotovar
Created October 12, 2018 17:58
Show Gist options
  • Save kevotovar/7b9df8eac7f1a8edecc3fac4e574acd4 to your computer and use it in GitHub Desktop.
Save kevotovar/7b9df8eac7f1a8edecc3fac4e574acd4 to your computer and use it in GitHub Desktop.
Convert object to django filter query params
function objectToQueryParams (obj) {
var params = '?';
var objectKeys = Object.keys(obj);
var objectLastItem = objectKeys.length - 1;
objectKeys.forEach(function(key, index) {
var currentValue = obj[key];
if (
typeof currentValue === 'object' &&
currentValue.length
) {
var arrayLastItem = currentValue.length - 1;
currentValue.forEach(function(arrayItem, arrayIndex) {
params = params + key + '=' + arrayItem;
if (arrayLastItem > arrayIndex) {
params = params + '&';
}
});
} else {
params = params + key + '=' + currentValue;
}
if (objectLastItem > index) {
params = params + '&';
}
});
return params;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment