2
\$\begingroup\$

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
\$\endgroup\$
0
4
\$\begingroup\$

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().

\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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!

\$\endgroup\$
2
  • \$\begingroup\$ {} -> '?' and {something:false} -> '?' are not correct results. \$\endgroup\$ – user1852503 Apr 22 '15 at 20:42
  • \$\begingroup\$ ah sry. Brain-fart from my side. \$\endgroup\$ – Hulvej May 4 '15 at 6:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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