Remove empty values from object javascript code example
Example 1: javascript remove empty object items
var test = {
test1: null,
test2: 'somestring',
test3: 3,
}
function clean(obj) {
for (var propName in obj) {
if (obj[propName] === null || obj[propName] === undefined) {
delete obj[propName];
}
}
return obj
}
console.log(test);
console.log(clean(test));
Example 2: es6 remove empty property from object
Object.entries(obj).reduce((a,[k,v]) => (v == null ? a : (a[k]=v, a)), {})