2705. Compact Object
Given a JSON-compatible object or array obj, return a compact version of the object — one without any falsy values at any level.
📄 Problem Statement
A compact object is one that has all falsy values removed recursively:
- Falsy values include:
false,0,"",null,undefined, andNaN. - Nested objects and arrays must also be compacted.
- The input is guaranteed to be valid JSON (i.e., no functions or undefined outside of parsing context).
- Arrays are treated as objects with numeric keys and must also be filtered.
💡 Example
const obj = {
a: null,
b: [false, 1],
c: {
d: 0,
e: "test",
f: {
g: NaN,
}
}
};
compactObject(obj);
// ➞ {
// b: [1],
// c: {
// e: "test"
// }
// }
🧠 Explanation
Recursively iterate through all keys of the object:
- If the value is an object or array, apply
compactObject()recursively. - If the result is still truthy, include it in the result.
- For arrays, only keep values that are truthy or resolve to truthy after recursion.
The logic leverages Boolean(value) to check for truthiness.
✅ Your Solution
/**
* @param {Object|Array} obj
* @return {Object|Array}
*/
var compactObject = function(obj) {
if (Array.isArray(obj)) {
return obj
.map(item => compactObject(item))
.filter(Boolean);
} else if (obj !== null && typeof obj === "object") {
const res = {};
for (const [key, value] of Object.entries(obj)) {
const compacted = compactObject(value);
if (Boolean(compacted)) {
res[key] = compacted;
}
}
return res;
}
return obj;
};