0

I want to find if the next value in a object exists or not, if it exists, add '&' else add nothing .

serializeForQueryString: function(obj) {
    var queryString ='';

    for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
            queryString=queryString+key+'='+ obj[key];

            if (obj.hasOwnProperty(key)!=null){
                queryString=queryString+'&';
            }
            alert(queryString);
        }
    }

    //document.write(obj.name);
    var queryString = '';

    //jquery
    //$.each(obj, function(key, value) {});

    //$.isArray

    return queryString;
},
2
  • 1
    So something like $.param()? Commented May 1, 2013 at 3:46
  • 1
    Make sure you use "encodeURIComponent" on keys and values if you use your own solution Commented May 1, 2013 at 3:50

1 Answer 1

2

Just build an array and then join it using &:

for (var key in obj) {
            if (obj.hasOwnProperty(key)) {

                 queryString.push(key + '=' + obj[key]);


            }
 }

queryString.join('&');
Sign up to request clarification or add additional context in comments.

5 Comments

I think you mean: querystring.push(key + "=" + obj[key]);
It would also be wise to url escape at least obj[key].
I agree, but I figured as the question was specifically about how to get the amperstand in between key value pairs, I would just show that.
This is a bad answer because it does not encode the data. Try to decode the query string that it produces if there is anything complicated contained in obj[key]. What if your object contains a value of 'x = 5 & y = 7' for example?
Then he should definitely URL encode it. However, the problem was to "find if the next value in a object exists or not, if it exists, add '&' else add nothing." Url-encoding is outside the scope of the question asked. Anyways - he has your comment, and other people mentioning the same thing, so I'm sure he and anyone else can figure it out.

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.