Last active
August 29, 2015 14:13
-
-
Save nherment/0914065cd54e1720953d to your computer and use it in GitHub Desktop.
JS make objects serializable
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 makeSerializable(obj, skipAttributes) { | |
if(_.isArray(obj)) { | |
var serializableArray = {} | |
for(var i = 0 ; i < obj.length ; i++) { | |
serializableArray[i] = makeSerializable(obj[i]) | |
} | |
return serializableArray | |
} else if(obj instanceof Object) { | |
var serializableObject = {} | |
for(var attr in obj) { | |
if(skipAttributes && _.contains(skipAttributes, attr)) { continue } | |
switch(typeof obj[attr]) { | |
case 'string': | |
case 'number': | |
case 'boolean': | |
serializableObject[attr] = obj[attr] | |
break | |
case 'object': | |
serializableObject[attr] = makeSerializable(obj[attr]) | |
break | |
} | |
} | |
return serializableObject | |
} else { | |
switch(typeof obj) { | |
case 'string': | |
case 'number': | |
case 'boolean': | |
return obj | |
break | |
case 'object': | |
return obj.toString() | |
break | |
} | |
return obj.toString() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
untested