Created
October 12, 2018 17:58
-
-
Save kevotovar/7b9df8eac7f1a8edecc3fac4e574acd4 to your computer and use it in GitHub Desktop.
Convert object to django filter query params
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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