Given an object or array obj, return a compact object. A compact object is the same as the original object but with keys containing falsy values removed. This operation should be applied to the object and its nested objects. Arrays are treated as objects with indices as keys, and any index with a falsy value is removed.
You can assume obj is the result of JSON.parse. In other words, it is valid JSON.
// Example 1:
Input: obj = [null, 0, false, 1]
Output: [1]
Explanation: All falsy values in the array have been removed.
// Example 2:
Input: obj = {"a": null, "b": [false, 1]}
Output: {"b": [1]}
Explanation: obj["a"] and obj["b"][0] contain falsy values, so they are removed.
function compactObject (obj){
if(typeof obj !== 'object' || obj === null){
return obj
}
if(Array.isArray(obj)){
return obj.map(value => compactObject(value)).filter(Boolean)
}
const result = {}
for (const key in obj) {
const value = compactObject(obj[key])
if (value) {
result[key] = value
}
}
return result;
}