Skip to content
Advertisement

Mapping object to key=value string in one line

Is there a way to convert this object:

{
    lang: 'en-us',
    episode: 12
}

To a string with the following format?

"lang=en-us&episode=12"

Much like mapping an object to a query string, where each property is a query parameter.

I can do it like this:

var parameters = [];
for(var prop in obj)
   parameters.push(prop + '=' + obj[prop]);
return parameters.join('&');

But I was looking for a one-line solution. Is this possible?

PS: I cannot use jQuery and any of it utility functions. The solution must be in pure JavaScript.

Advertisement

Answer

You can use Array.prototype.map on the Object.keys array:

var data = {"lang": "en-us", "episode": 12};
var str = Object.keys(data).map(function (key) { 
  return "" + key + "=" + data[key]; // line break for wrapping only
}).join("&");
console.log(str);

With ES6, this becomes even more terse:

var data = {"lang": "en-us", "episode": 12};
var str = Object.keys(data).map(key => `${key}=${data[key]}`).join("&");
console.log(str);
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement