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

Reason for making this was that I wanted to print out some objects to the console, that might be concatenated with strings. If you try to just say window.console.log(someObject);, then what gets put out is the string representation of that object, complete with key value pairs and brackets and commas, etc. If you try to do the same thing, but with a string concatenated with it, like: window.console.log("some text" + someObject); then you get this echoed out: "some text [object Object]" I wanted the string representation complete with brackets, commas, key and value pairs, etc., so I wrote this function.

Now I can do this and it will do the right thing:

window.console.log("some text" + objectToString(someObject));

@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