LeetcodeDec 04, 2025

Compact Object

Hazrat Ali

Leetcode

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.


Solution
var compactObject = function(obj) {
    if (obj === null) return null;  
 
    if (Array.isArray(obj)) {
        const result = [];
        for (const item of obj) {
            const compacted = compactObject(item);
            if (Boolean(compacted)) {  
                result.push(compacted);
            }
        }
        return result;
    }

   
    if (typeof obj === "object") {
        const result = {};
        for (const key in obj) {
            const compacted = compactObject(obj[key]);
            if (Boolean(compacted)) {  
                result[key] = compacted;
            }
        }
        return result;
    }

   
    return obj;
};
 

Comments