How is the data being processed in the function?

0107

The data is processed in the compactObject() function using the following steps:

  1. Initialization: The function checks if the input val is an array. If it is, it filters out all falsy values using filter(Boolean). If it's not an array, it assigns val directly to data.

  2. Iteration: It uses Object.keys(data) to get all the keys of the object or array and iterates over them with reduce().

  3. Truthiness Check: For each key, it checks the truthiness of the value. If the value is truthy, it adds it to the accumulator.

  4. Recursion: If the value is an object, the function calls itself recursively to deeply compact that object.

  5. 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.

0 Comments

no data
Be the first to share your comment!