Last active
April 6, 2018 16:02
-
-
Save joewright/151e457e440d2f01b86fc153a8487ffc to your computer and use it in GitHub Desktop.
js omitValuesRecursive
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
var dang = {dang: '', haha: '', whoops: undefined, whatever: false, hehe: [{what: '', lol: true, ok: false, wow: {haha: 'false', word: [], up: '', ok: false }, why: 0 }, null, 'lol' - 42] }; | |
function omitValuesRecursive(obj, omittedValues) { | |
var omittedValues = omittedValues || ['', undefined, null]; | |
if (window._) { | |
return scrubEmptyFieldsLodash(obj); | |
} | |
return scrubEmptyFields(obj); | |
// recursively remove omitted values from the object. modifies the original object | |
function scrubEmptyFields(obj) { | |
for (var field in obj) { | |
if (Array.isArray(obj[field])) { | |
obj[field] = obj[field].map(function(item) { | |
return scrubEmptyFields(item); | |
}).filter(function(item) { | |
return omittedValues.indexOf(item) === -1 && !Number.isNaN(item); | |
}); | |
} else if (obj[field] !== null && typeof obj[field] === 'object') { | |
obj[field] = scrubEmptyFields(obj[field]); | |
} else if (omittedValues.indexOf(obj[field]) !== -1 || Number.isNaN(obj[field])) { | |
delete obj[field]; | |
} | |
} | |
return obj; | |
} | |
// with lodash | |
function scrubEmptyFieldsLodash(obj) { | |
_.forIn(obj, function(value, key) { | |
if (_.isArray(value)) { | |
obj[key] = _.chain(value) | |
.map(function(item) { | |
if (omittedValues.indexOf(item) === -1 && !_.isNaN(item)) { | |
return scrubEmptyFieldsLodash(item); | |
} | |
}) | |
.compact() | |
.value(); | |
} else if (value !== null && typeof value === 'object') { | |
obj[key] = scrubEmptyFieldsLodash(value); | |
} else if (omittedValues.indexOf(value) !== -1 || _.isNaN(value)) { | |
delete obj[key]; | |
} | |
}); | |
return obj; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment