Last active
December 16, 2015 12:28
-
-
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.
This file contains hidden or 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 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