Compact Object - Problem
Given an object or array obj, return a compact object.
A compact object is the same as the original object, except with keys containing falsy values removed. This operation applies to the object and any nested objects. Arrays are considered objects where the indices are keys. A value is considered falsy when Boolean(value) returns false.
You may assume the obj is the output of JSON.parse. In other words, it is valid JSON.
Input & Output
Example 1 — Object with Falsy Values
$
Input:
obj = {"a": null, "b": [false, 1]}
›
Output:
{"b": [1]}
💡 Note:
The key 'a' is removed because null is falsy. In the array [false, 1], false is removed but 1 remains as it's truthy.
Example 2 — Array with Mixed Values
$
Input:
obj = [null, 0, 5, [0], {}]
›
Output:
[5, []]
💡 Note:
null and 0 are falsy and removed. 5 remains. [0] becomes [] after removing 0. {} remains as an empty object.
Example 3 — Nested Objects
$
Input:
obj = {"a": {"b": {"c": 0}}}
›
Output:
{}
💡 Note:
The value 0 is falsy, so it's removed. This makes object {"c": 0} become {}, then the parent objects cascade to become empty, resulting in {}.
Constraints
- obj is a valid JSON object
- obj only contains JSON data types: null, boolean, number, string, object, array
- 2 ≤ JSON.stringify(obj).length ≤ 106
- Nested depth ≤ 1000
Visualization
Tap to expand
Understanding the Visualization
1
Input
Original object/array with falsy values mixed in
2
Process
Recursively filter out falsy values (null, false, 0, "")
3
Output
Compacted structure with only truthy values
Key Takeaway
🎯 Key Insight: Recursively traverse nested structures and filter out values that evaluate to false in Boolean context
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code