Compact Object Problem
Description
LeetCode Problem 2705.
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.
Example 1:
Input: obj = [null, 0, false, 1]
Output: [1]
Explanation: All falsy values have been removed from the array.
Example 2:
Input: obj = {"a": null, "b": [false, 1]}
Output: {"b": [1]}
Explanation: obj["a"] and obj["b"][0] had falsy values and were removed.
Example 3:
Input: obj = [null, 0, 5, [0], [false, 16]]
Output: [5, [], [16]]
Explanation: obj[0], obj[1], obj[3][0], and obj[4][0] were falsy and removed.
Constraints:
objis a valid JSON object2 <= JSON.stringify(obj).length <= 10^6
Solution
Approach: Recursive filter
Handle the three kinds of value:
- A primitive (including
null) is returned unchanged; the caller already decided it is truthy. - An array: drop the falsy elements with
filter(Boolean), then compact each remaining element. - An object: keep a key only when its value is truthy, and store the compacted value.
Falsy is checked on the original value, before recursing, so an empty array or object (which is truthy) is kept, as in [0] becoming [] inside the result of Example 3. The result of the object case is built with Object.fromEntries, which also copes with a key such as "__proto__" from JSON.parse.
Complexity: Time O(n) in the number of values, space O(depth) plus the output.
var compactObject = function (obj) {
if (obj === null || typeof obj !== 'object') return obj;
if (Array.isArray(obj)) {
return obj.filter(Boolean).map(compactObject);
}
return Object.fromEntries(
Object.entries(obj)
.filter(([, value]) => Boolean(value))
.map(([key, value]) => [key, compactObject(value)]),
);
};