9

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.

0

3 Answers 3

8

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()
Sign up to request clarification or add additional context in comments.

2 Comments

I think this is the best solution. Seems like the $.param() method should accept a third parameter, something like includeEmpty.
@AndrewMairose caref
1

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("&");
}

Comments

0

Here you can exclude the null values, keeping your properties in your object: https://jsfiddle.net/leojavier/bxc57o3v/2/

var queryParams = {
        firstNm: null,
        lastNm: 'M',
        id: null,
        email: null
    }
    var query = {}
    for(item in queryParams) {
        if(queryParams[item] != null && queryParams[item].length > 0) {
            query[item] = queryParams[item]
            console.log(query)
            console.log($.param(query));
        }
    }

1 Comment

Good idea, but in my case, it's fine to delete the properties, because I am immediately redirecting to a new page that includes the serialized object as parameters in the URL

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.