Skip to content

Instantly share code, notes, and snippets.

@Kyle-Falconer
Created October 25, 2013 18:31
Show Gist options
  • Save Kyle-Falconer/7159537 to your computer and use it in GitHub Desktop.
Save Kyle-Falconer/7159537 to your computer and use it in GitHub Desktop.
toString function for an object with key:value pairs.
function objectToString(obj){
var result = [];
result.push('{ ');
for (var key in obj){
if (result.length > 1){
result.push(', ');
}
result.push(key+' : ');
var value;
if (typeof obj[key] === 'undefined'){
value = 'undefined';
} else if (obj[key] === null){
value = 'null';
} else if (typeof obj[key] === 'string' || obj[key] instanceof String ){
value = '"'+obj[key]+'"';
} else if (obj[key] instanceof Object){
value = objectToString(obj[key]);
} else {
value = obj[key];
}
result.push(value);
}
result.push(' }');
return result.join('');
};
@Kyle-Falconer
Copy link
Author

Aaaand, as it usually turns out, this is already implemented in vanilla JavaScript via the JSON.stringify method. Oh well. If anyone's interested in the sauce for that, it's on Douglas Crockford's GitHub.

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