In JavaScript, it’s common to encounter objects and arrays that contain values considered ‘falsy,’ such as null, 0, "" (empty string), false, undefined, or NaN. Often, for cleaner data structures or specific processing, you’ll want to remove these falsy entries, effectively ‘compacting’ your data.

This article introduces a versatile JavaScript function, compactObject, designed precisely for this task. It efficiently traverses nested objects and arrays, eliminating any property or element that evaluates to false when cast to a Boolean.

How the compactObject Function Works

The compactObject function operates recursively:

  1. Base Case: If the input obj is not an object or is null, it’s returned as is. This handles primitive values directly.
  2. Initialization: It determines if the input is an array or an object and initializes an empty array or object (result) accordingly.
  3. Iteration: It iterates through each key-value pair of the input obj.
  4. Recursive Call: For each value, it recursively calls compactObject(value). This ensures that nested structures are also compacted.
  5. Falsy Check: After receiving the compactedValue from the recursive call, it checks if Boolean(compactedValue) is true. Only truthy values are retained.
  6. Reconstruction: The truthy compactedValue is then added to the result (either pushed to an array or assigned to a property in an object).
  7. Return: Finally, the result (a new object or array containing only truthy, compacted values) is returned.

The compactObject JavaScript Code

Here’s the implementation of the compactObject function:

/**
 * @param {Object|Array} obj
 * @return {Object|Array}
 */
var compactObject = function (obj) {
    if (typeof obj !== 'object' || obj == null) {
        return obj;
    }
    const isArray = Array.isArray(obj);
    const result = isArray ? [] : {};
    const keys = Object.keys(obj);
    for (const key of keys) {
        let value = obj[key];
        let compactedValue = compactObject(value);
        if (Boolean(compactedValue)) {
            if (isArray) {
                result.push(compactedValue);
            } else {
                result[key] = compactedValue;
            }
        }
    }
    return result;
};

Example Usage

Let’s see compactObject in action:

const exampleObject = {
    a: 1,
    b: null,
    c: "hello",
    d: undefined,
    e: [1, 0, "world", false],
    f: {
        g: true,
        h: "",
        i: [{}, null, "test"]
    },
    j: 0
};

const compacted = compactObject(exampleObject);
console.log(compacted);

/*
Expected Output:
{
  a: 1,
  c: "hello",
  e: [1, "world"],
  f: {
    g: true,
    i: [{}, "test"]
  }
}
*/

Notice how null, undefined, 0, "", and false (including the 0 and false inside the nested array e, and the empty string h) have all been removed. Empty objects within arrays that remain empty after compaction are kept, as {} itself is a truthy value.

You can view a live demonstration of this function here: https://leetcode-compact-object.netlify.app/

This compactObject function provides a clean and efficient way to sanitize your JavaScript data structures, ensuring you only work with meaningful, truthy values.

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed