The data is processed in the compactObject() function using the following steps:
-
Initialization: The function checks if the input
valis an array. If it is, it filters out all falsy values usingfilter(Boolean). If it's not an array, it assignsvaldirectly todata. -
Iteration: It uses
Object.keys(data)to get all the keys of the object or array and iterates over them withreduce(). -
Truthiness Check: For each key, it checks the truthiness of the value. If the value is truthy, it adds it to the accumulator.
-
Recursion: If the value is an object, the function calls itself recursively to deeply compact that object.
-
Return: Finally, it returns a new object or array with all falsy values removed.
Here’s the code for reference:
const compactObject = (val) => {
const data = Array.isArray(val) ? val.filter(Boolean) : val;
return Object.keys(data).reduce(
(acc, key) => {
const value = data[key];
if (Boolean(value))
acc[key] = typeof value === "object" ? compactObject(value) : value;
return acc;
},
Array.isArray(val) ? [] : {},
);
};
You can use this function by passing an object or array to it, and it will return a compacted version without any falsy values.
