Skip to content

Instantly share code, notes, and snippets.

@JamieMason
Created June 21, 2011 15:57
Show Gist options
  • Save JamieMason/1038177 to your computer and use it in GitHub Desktop.
Save JamieMason/1038177 to your computer and use it in GitHub Desktop.
Apply similar behaviour to Array.join to an Object
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);
};
@JamieMason
Copy link
Author

Three quick examples below...

var oExample = {
    age: 28
    , forename: 'Jamie'
    , github: 'https://github.com/JamieMason'
    , surname: 'Mason'
},
oLogging = {
    'No Arguments': oExample.join()
    , 'With seperator': oExample.join(' | ')
    , 'With seperator and template': oExample.join(',\n', '<strong>{key}</strong> {value}')
    , 'With seperator and template (2)': oExample.join('\n', '{key} ({value})')
};

console.log(oLogging.join('\n\n', '{key}\n-----\n{value}'));

@JamieMason
Copy link
Author

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