I am using jQuery's $.param()
to serialize an object in the following format:
var queryParams = {
firstNm: null,
lastNm: 'M',
id: null,
email: null
}
When I use $.param(queryParams)
, I get the following:
firstNm=&lastNm=M&id=&email=
What I would like to have instead is simply:
lastNm=M
I would like any parameters that are null or empty to not show up in the output. Is this possible using jQuery's $.param()
, or will it require custom serialization?
EDIT:
This is NOT a duplicate of this question. That question pertains more to the MediaWiki API and has to do with not including the =
when a parameter is null or empty, and only including the key of the key value pair. My question is whether it is possible to leave off the key value pair entirely from the output if the value is null or empty.
You can write your own function to exclude null and empty values:
var queryParams = {
firstNm: null,
lastNm: 'M',
id: null,
email: null
}
function isEmpty(value){
return value == null || value == "";
}
for(key in queryParams)
if(isEmpty(queryParams[key]))
delete queryParams[key];
// queryParams now = { lastNm: "M"}
and if you get this values from form you can do the following:
$("#form :input[value!='']").serialize()
Another alternative to achieve removal of empty parameters in the serialized string.
var serializeURLParameters = function(oParameters) {
return "?" + Object.keys(oParameters).map(function(key) {
if(oParameters[key]) {
return key + "=" + encodeURIComponent(oParameters[key]);
}
}).filter(function(elem) {
return !! elem;
}).join("&");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With