Skip to content

Instantly share code, notes, and snippets.

@pedrombafonso
Last active December 16, 2015 12:28
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 pedrombafonso/5434541 to your computer and use it in GitHub Desktop.
Save pedrombafonso/5434541 to your computer and use it in GitHub Desktop.
Cleans JSON objects by removing undesired properties and promoting nested objects (set parent = child) recursively.
/*
@function cleanObject - Cleans javascript objects recursively (removes and promotes [parent = child] properties)
@param {Object} obj - Object to be clean
@param {Array} toRemove - array composed by the property names to be removed
@param {Array} toPromote - array composed by the property names to be promoted to the parent's value
*/
function cleanObject(dirtyObj, toRemove, toPromote) {
var obj = JSON.parse(JSON.stringify(dirtyObj));
var itemsObj;
var o;
for (o in obj) {
if (toRemove.indexOf(o) !== -1) {
delete obj[o];
} else {
if (toPromote.indexOf(o) !== -1) {
itemsObj = obj[o];
obj[o] = cleanObject(obj[o], toRemove, toPromote);
} else if (typeof obj[o] === 'object') {
obj[o] = cleanObject(obj[o], toRemove, toPromote);
}
}
}
return itemsObj || obj;
}
function testCleanObject() {
var dirtyObject = {
"child": {
"listAllSelectedIndices": [],
"items": [
{
"fakeToken": "1"
},
{
"fakeToken": "2"
}
]
}
};
var cleanedObject = {
"child": [
{
"fakeToken": "1"
},
{
"fakeToken": "2"
}
]
};
var outputObject = cleanObject(dirtyObject, ['listAllSelectedIndices'], ['items']);
// console.log(cleanedObject);
console.log(outputObject);
assert(JSON.stringify(outputObject) === JSON.stringify(cleanedObject), "");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment