Skip to content

Instantly share code, notes, and snippets.

@tlbdk
Last active November 21, 2016 09:19
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 tlbdk/fe0d9f671e3dfd92da00a67665630659 to your computer and use it in GitHub Desktop.
Save tlbdk/fe0d9f671e3dfd92da00a67665630659 to your computer and use it in GitHub Desktop.
Non-recursive deep stripping on null values in two version clone/non-clone
var obj = {
a: 1,
b: null,
c: [
{
d: null,
e: 'something'
}
]
};
console.log("Orginal:");
console.info(obj);
console.log("stripNullDeepClone:");
var obj2 = stripNullDeepClone(obj);
console.info(obj2);
console.info(obj);
console.log("stripNullDeep:");
stripNullDeep(obj);
console.info(obj);
function stripNullDeep(obj) {
var seen = {};
var objs = [obj];
while(objs.length > 0) {
obj = objs.shift();
for(key in obj) {
if (obj[key] === null) {
delete obj[key];
} else if(typeof obj[key] === 'object') { // Also matches arrays
objs.push(obj[key]);
}
}
}
}
function stripNullDeepClone(obj) {
var result = Object.assign({}, obj);
var objs = [result];
while(objs.length > 0) {
obj = objs.shift();
for(key in obj) {
if (obj[key] === null) {
delete obj[key];
} else if(typeof obj[key] === 'object') {
obj[key] = Array.isArray(obj[key]) ? obj[key].slice(0) : Object.assign({}, obj[key]);
objs.push(obj[key]);
}
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment