Skip to content

Instantly share code, notes, and snippets.

@christopherdebeer
Forked from mikeal/gist:2331127
Created April 7, 2012 19:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christopherdebeer/2331687 to your computer and use it in GitHub Desktop.
Save christopherdebeer/2331687 to your computer and use it in GitHub Desktop.
safe .toJSON()
function getSafe (self, uuid) {
if (typeof self === 'object' || typeof self === 'function') var safe = {}
if (Array.isArray(self)) var safe = []
var recurse = []
Object.defineProperty(self, uuid, {})
var attrs = Object.keys(self).filter(function (i) {
if (i === uuid) return false
if ( (typeof self[i] !== 'object' && typeof self[i] !== 'function') || self[i] === null) return true
return !(Object.getOwnPropertyDescriptor(self[i], uuid))
})
for (var i=0;i<attrs.length;i++) {
if ( (typeof self[attrs[i]] !== 'object' && typeof self[attrs[i]] !== 'function') ||
self[attrs[i]] === null
) {
safe[attrs[i]] = self[attrs[i]]
} else {
recurse.push(attrs[i])
Object.defineProperty(self[attrs[i]], uuid, {})
}
}
for (var i=0;i<recurse.length;i++) {
safe[recurse[i]] = getSafe(self[recurse[i]], uuid)
}
return safe
}
function toJSON () {
return getSafe(this, (((1+Math.random())*0x10000)|0).toString(16))
}
// MyObject.prototype.toJSON = toJSON
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment