Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping object to key=value string in one line

Tags:

javascript

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.

like image 866
Matias Cicero Avatar asked Aug 23 '26 11:08

Matias Cicero


2 Answers

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);
like image 54
ssube Avatar answered Aug 26 '26 02:08

ssube


You could use

var myObj ={"lang": "en-us", "episode": 12};
var str = Object.keys(myObj).map(key => key+"="+myObj[key]).join("&");

Whether or not this is any more readable is another question :)

like image 21
Deftwun Avatar answered Aug 26 '26 00:08

Deftwun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!