Skip to content

Instantly share code, notes, and snippets.

@nherment
Last active August 29, 2015 14:13
Show Gist options
  • Save nherment/0914065cd54e1720953d to your computer and use it in GitHub Desktop.
Save nherment/0914065cd54e1720953d to your computer and use it in GitHub Desktop.
JS make objects serializable
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()
}
}
@nherment
Copy link
Author

nherment commented Jan 7, 2015

untested

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