I am using the data sample from one of the answers here.
var data = {
emptyArray: [],
arrayWithNullish: [null, {}, [], undefined],
null: null,
undefined: undefined,
emptyString: '',
zero: 0,
false: false,
true: true,
emptyObject: {},
objectWithNullish: { null: null, emptyArray: [], undefined: undefined },
nestedObject: {
nestedObject: {
null: null,
one: 1,
emptyObject: {}
},
nestedEmptyArray: [[], [[]], 6]
}
};
function clean(data){
return (function inner(data, output){
if (!isObject(data)){
return data;
}
Object.keys(data).forEach(function(key){
if(isObject(data[key]) && !Array.isArray(data[key])){
var result = clean(data[key], output);
updateVal(output, key, result);
}else if(Array.isArray(data[key])){
var new_arr = [];
data[key].forEach(function(a_item){
var a_result = clean(a_item, output);
if (!isFalsy(a_result)){
new_arr.push(a_item);
}
});
updateVal(output, key, new_arr);
}else{
updateVal(output, key, data[key]);
}
});
return output;
})(data, {});
}
function updateVal(output,key, val){
if(!isFalsy(val)){
output[key] = val;
}
}
function isObject(data){
return typeof data === "object" && data !== null;
}
function isFalsy(val){
return ['', undefined, null].indexOf(val) !== -1 ?
true:
(()=>{
return typeof(val) === "object" && Object.keys(val).length === 0 ? true: false;
})();
}
console.log(clean(data));
[null, null, null]is a non-empty array, but also an object, that has three properties, which arenull. What to do here? Also, for an input of e.g.{ x: { y: null }}, i assume the removal should be done depth-first, and the result should be{}and not{ x: {}}?[null, null, null], the entire array and property should be removed. For{ x: { y: null } }we should get{}