Created
November 26, 2014 09:58
-
-
Save partageit/98dcffa403605189bc4b to your computer and use it in GitHub Desktop.
Returns a clean copy of the provided object, in order to JSON.stringify it for example
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
'use strict'; | |
/** | |
* Returns a clean copy of the provided object, in order to JSON.stringify it for example. | |
* | |
* It removes recursively methods and cyclic objects. | |
* Cyclic objects are references to a parent object of the property, for example: a.b.c = a; | |
* References to non-parent objects are kept, for example: a.b.c = 'hello'; a.d = a.b; | |
* @param any obj Any variable. When obj is not an object, it is returned as-is. | |
* @param array parents Parents list, for internal use. | |
* @return any The cleaned object | |
*/ | |
function getCleanObject(obj, parents) { | |
if (typeof obj !== 'object') { | |
return obj; | |
} | |
parents = parents || []; | |
parents.push(obj); | |
var newObject = {}; | |
for (var name in obj) { | |
if (obj.hasOwnProperty(name)) { | |
if (typeof obj[name] !== 'function') { | |
if (typeof obj[name] === 'object') { | |
if (parents.indexOf(obj[name]) === -1) { | |
newObject[name] = getCleanObject(obj[name], parents); | |
} | |
} else { | |
newObject[name] = obj[name]; | |
} | |
} | |
} | |
} | |
parents.splice(parents.indexOf(obj), 1); | |
return newObject; | |
} | |
/* | |
// Example: | |
var o = { 'a': 1 }; | |
o.cyclic = o; | |
o.string = 'in o'; | |
o.func = function() { return 'hello world!'; }; // should be removed | |
o.objectToKeep = { x: 1, y: 2 }; | |
o.objectWithAFunction = { | |
a: 5, | |
f: function() { return 'hello'; } // should be removed | |
}; | |
o.subCyclic = { | |
e: 6, | |
parent: o // should be removed | |
}; | |
o.objectReferencingObjectToKeep = { | |
a: 5, | |
f: function() { return 'hello'; }, | |
notAParent: o.objectToKeep // should be kept | |
}; | |
o.objectReferencingItself = { | |
a: 5, | |
f: function() { return 'hello'; } // should be removed | |
}; | |
o.objectReferencingItself.me = o.objectReferencingItself; // should be removed | |
o.subCyclic = { | |
e: 6, | |
parent: o // should be removed | |
}; | |
// here, o can not be JSON.stringified, as it contains cyclic references | |
console.log('Object: ', o); | |
var cleaned = getCleanObject(o); | |
console.log('Cleaned: ', cleaned); | |
var j = JSON.stringify(cleaned); | |
console.log('JSON: ', j); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment