Created
October 25, 2013 18:31
-
-
Save Kyle-Falconer/7159537 to your computer and use it in GitHub Desktop.
toString function for an object with key:value pairs.
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
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(''); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.