Last active
November 21, 2016 09:19
-
-
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
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
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