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:
- Base Case: If the input
objis not an object or isnull, it’s returned as is. This handles primitive values directly. - Initialization: It determines if the input is an array or an object and initializes an empty array or object (
result) accordingly. - Iteration: It iterates through each key-value pair of the input
obj. - Recursive Call: For each
value, it recursively callscompactObject(value). This ensures that nested structures are also compacted. - Falsy Check: After receiving the
compactedValuefrom the recursive call, it checks ifBoolean(compactedValue)istrue. Only truthy values are retained. - Reconstruction: The truthy
compactedValueis then added to theresult(either pushed to an array or assigned to a property in an object). - 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.