Created
June 21, 2011 15:57
-
-
Save JamieMason/1038177 to your computer and use it in GitHub Desktop.
Apply similar behaviour to Array.join to an Object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Object.prototype.join = function (separator, template) | |
{ | |
var key | |
, output = [] | |
, length = 0 | |
, self = this | |
, tKey = '{key}' | |
, tValue = '{value}'; | |
separator = separator || ','; | |
template = template || [tKey, tValue].join(':'); | |
for (key in self) | |
{ | |
if (self.hasOwnProperty(key)) | |
{ | |
output[length++] = template.split(tKey).join(key).split(tValue).join(this[key]); | |
} | |
} | |
return output.join(separator); | |
}; |
Above example outputs...
No Arguments
-----
age:28,forename:Jamie,github:https://github.com/JamieMason,surname:Mason
With seperator
-----
age:28 | forename:Jamie | github:https://github.com/JamieMason | surname:Mason
With seperator and template
-----
<strong>age</strong> 28,
<strong>forename</strong> Jamie,
<strong>github</strong> https://github.com/JamieMason,
<strong>surname</strong> Mason
With seperator and template (2)
-----
age (28)
forename (Jamie)
github (https://github.com/JamieMason)
surname (Mason)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Three quick examples below...