Object to query string 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 =&gt; obj[key] !== '' &amp;&amp; obj[key] !== null)
            .map((key, index) =&gt; {
            var startWith = index === 0 ? '?' : '&amp;';
            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&amp;maxDistance=1000&amp;ownerName=cindy
You have neglected to escape your keys and values. If any of the data contains a special character such as &amp;, the generated URL will be wrong.

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