Skip to content

Instantly share code, notes, and snippets.

@lucasdavila
Last active February 24, 2023 17:40
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save lucasdavila/4331999 to your computer and use it in GitHub Desktop.
Save lucasdavila/4331999 to your computer and use it in GitHub Desktop.
Joining javascript key-value objects as string.
Object.prototype.join = function(glue, separator) {
var object = this;
if (glue == undefined)
glue = '=';
if (separator == undefined)
separator = ',';
return Object.keys(object).map(function (key, value) { return [key, value].join(glue); }).join(separator);
}
var options = { id : 1, name : 'lucas', country : 'brasil'};
options.join();
> "id=1,name=lucas,country=brasil"
options.join('=>', ' ');
> "id=>1 name=>lucas country=>brasil"
@alitoufighi
Copy link

Object.keys(object).map((key) => [key, options[key]].join(glue)).join(separator)

@cccabdalla
Copy link

cccabdalla commented Jan 21, 2021

Object.keys(object).map((key) => [key, options[key]].join(glue)).join(separator)

@alitoufighi, I was wondering where $ came from but your fix is very helpful and worked as expected. Thank U.

@lucasdavila
Copy link
Author

@cccabdalla the $ was a reference to the global jquery object, the original code is a bit old.

I will update it with the suggestion @alitoufighi sent, thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment