Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

An object (POJO) holds query arguments and has two-binding to a form using some MVC framework. later the object needs to be converted to a query string that will be appended to an HTTP request.

function objectToQueryString(obj) {
        return Object.keys(obj)
            .filter(key => obj[key] !== '' && obj[key] !== null)
            .map((key, index) => {
            var startWith = index === 0 ? '?' : '&';
            return startWith + key + '=' + obj[key]
        }).join('');
    }

Any pitfalls? IE9+ is what we support.

Example input:

{isExpensive:true, maxDistance:1000,ownerName:'Cindy',comment:''}

And its expected output:

?isExpensive=true&maxDistance=1000&ownerName=cindy
share|improve this question
    
Can you provide an example obj for reference? –  Quill Apr 20 at 22:34
    
@Quill added example of input output. –  user1852503 Apr 20 at 22:43

3 Answers 3

up vote 4 down vote accepted

You have neglected to escape your keys and values. If any of the data contains a special character such as &, the generated URL will be wrong.

To perform the escaping, I recommend calling encodeURIComponent().

share|improve this answer

You could do it a bit simpler as well:

function objectToQueryString(obj) {
   var query = Object.keys(obj)
       .filter(key => obj[key] !== '' && obj[key] !== null)
       .map(key => key + '=' + obj[key])
       .join('&');
   return query.length > 0 ? '?' + query : null;
}

And yes, if you don't have a shim for es6 you need to use the verbose notation. I can recommend es6-shim for this!

share|improve this answer
    
{} -> '?' and {something:false} -> '?' are not correct results. –  user1852503 Apr 22 at 20:42
    
ah sry. Brain-fart from my side. –  Hulvej May 4 at 6:53

At the time of this post, arrow functions in JavaScript (=>) are an experimental/proposed technology supported only by Firefox, with no stable specification.

If you need to support IE9, IE10, IE11, Chrome, Opera, or Safari, you'll want to use the more verbose function expressions that they replace.

As 200_Success noted, you'll want to encode the values returned, and also decode them when translating the encoded query string back into the original string. You can use encodeURIComponent() and decodeURIComponent() for this.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.