Skip to main content

Object & Array Utilities

A collection of utility functions for manipulating objects, arrays, and complex data structures used throughout the WorkPayCore frontend application.

Object Manipulation Functions

removeFalsy(obj)

Removes all falsy properties from an object, creating a clean object with only truthy values.

Parameters:

  • obj (object): The object to clean

Returns:

  • object: A new object with falsy values removed

Example:

const dirtyObj = {
name: 'John',
age: 0,
email: '',
active: true,
address: null,
phone: '123-456-7890',
};

const cleanObj = removeFalsy(dirtyObj);
// Returns: { name: 'John', active: true, phone: '123-456-7890' }

Use Cases:

  • Cleaning form data before API submission
  • Removing empty fields from user input
  • Preparing data for storage or processing

IsEmpty(values)

Checks if an object is empty (has no truthy values).

Parameters:

  • values (object): The object to check

Returns:

  • boolean: True if the object is empty or has no truthy values

Example:

const emptyObj = {};
const nullObj = { name: null, age: '', active: false };
const validObj = { name: 'John', age: 30 };

IsEmpty(emptyObj); // Returns: true
IsEmpty(nullObj); // Returns: true
IsEmpty(validObj); // Returns: false

Use Cases:

  • Validating form completeness
  • Checking if data exists before processing
  • Conditional rendering based on data presence

isLiteralObject(param)

Checks if a parameter is a literal object (plain object created with {} or new Object()).

Parameters:

  • param (any): The parameter to check

Returns:

  • boolean: True if the parameter is a literal object

Example:

isLiteralObject({}); // Returns: true
isLiteralObject({ a: 1 }); // Returns: true
isLiteralObject(new Date()); // Returns: false
isLiteralObject([]); // Returns: false
isLiteralObject(null); // Returns: false

Use Cases:

  • Type checking before object operations
  • Validating configuration objects
  • Ensuring data structure integrity

Array Manipulation Functions

removeFalsyFromArray(array)

Removes all falsy values from an array.

Parameters:

  • array (array): The array to clean

Returns:

  • array: A new array with falsy values removed

Example:

const dirtyArray = ['hello', '', 0, 'world', null, undefined, false, 'test'];
const cleanArray = removeFalsyFromArray(dirtyArray);
// Returns: ['hello', 'world', 'test']

Use Cases:

  • Cleaning user input arrays
  • Filtering out empty selections
  • Preparing arrays for processing

removeFalsyObjectFromArray(array)

Removes objects from an array if any of their properties contain falsy values.

Parameters:

  • array (array): Array of objects to filter

Returns:

  • array: A new array with objects containing falsy values removed

Example:

const users = [
{ name: 'John', email: 'john@example.com', active: true },
{ name: '', email: 'jane@example.com', active: true },
{ name: 'Bob', email: null, active: true },
{ name: 'Alice', email: 'alice@example.com', active: false },
];

const validUsers = removeFalsyObjectFromArray(users);
// Returns: [{ name: 'Alice', email: 'alice@example.com', active: false }]
// Note: Only Alice remains because others have falsy values (empty name, null email)

Use Cases:

  • Validating data completeness in arrays
  • Filtering incomplete records
  • Data quality assurance

IsEmptyArray(arr)

Checks if the provided argument is an empty array with proper type checking.

Parameters:

  • arr (Array<any>): The array to check

Returns:

  • boolean: Returns true if the argument is an array and it's empty, false otherwise

Example:

IsEmptyArray([]); // Returns: true
IsEmptyArray([1, 2, 3]); // Returns: false
IsEmptyArray('not an array'); // Returns: true (not an array)
IsEmptyArray(null); // Returns: true (not an array)

Use Cases:

  • Safe array validation before iteration
  • Conditional rendering based on array content
  • Preventing runtime errors with non-array inputs

Data Transformation Functions

v2EmployeeOptionsList(empArr)

Transforms an array of employee objects into a format suitable for dropdown/select components.

Parameters:

  • empArr (array): Array of employee objects with nested person data

Returns:

  • array: Array of option objects with value, label, and employee properties

Example:

const employees = [
{
person: { id: 1, first_name: 'John', surname: 'Doe' },
department: 'Engineering',
},
{
person: { id: 2, first_name: 'Jane', surname: 'Smith' },
department: 'Marketing',
},
];

const options = v2EmployeeOptionsList(employees);
// Returns: [
// { value: 1, label: 'John Doe', employee: { person: {...}, department: 'Engineering' } },
// { value: 2, label: 'Jane Smith', employee: { person: {...}, department: 'Marketing' } }
// ]

Use Cases:

  • Creating employee selection dropdowns
  • Formatting data for React Select components
  • Maintaining reference to original employee data

extractValuesByKeys(sourceObject, keys)

Extracts the .value property from specified keys in an object, useful for form data processing.

Parameters:

  • sourceObject (object): The object containing nested .value properties
  • keys (Array<string>): The array of keys to extract values from

Returns:

  • object: An object mapping each key to its corresponding .value

Example:

const formData = {
name: { value: 'John Doe', error: null },
email: { value: 'john@example.com', error: null },
age: { value: 30, error: null },
department: { value: 'Engineering', error: 'Required' },
};

const extractedValues = extractValuesByKeys(formData, ['name', 'email', 'age']);
// Returns: {
// name: 'John Doe',
// email: 'john@example.com',
// age: 30
// }

Use Cases:

  • Processing controlled form inputs
  • Extracting clean data from complex form state
  • API payload preparation from form objects

Advanced Usage Examples

Complete Form Data Processing

// Original form with mixed data quality
const formSubmission = {
name: { value: 'John Doe', error: null },
email: { value: 'john@example.com', error: null },
phone: { value: '', error: 'Required' },
address: { value: null, error: null },
preferences: { value: 'email', error: null },
};

// Extract only the values
const values = extractValuesByKeys(formSubmission, [
'name',
'email',
'phone',
'address',
'preferences',
]);

// Remove falsy values for clean API payload
const cleanPayload = removeFalsy(values);
// Result: { name: 'John Doe', email: 'john@example.com', preferences: 'email' }

Data Validation Pipeline

const userRecords = [
{ id: 1, name: 'John', email: 'john@example.com', status: 'active' },
{ id: 2, name: '', email: 'jane@example.com', status: 'active' },
{ id: 3, name: 'Bob', email: null, status: 'inactive' },
{ id: 4, name: 'Alice', email: 'alice@example.com', status: '' },
];

// Step 1: Remove records with any falsy values
const completeRecords = removeFalsyObjectFromArray(userRecords);

// Step 2: Check if we have any valid records
if (!IsEmptyArray(completeRecords)) {
// Process the clean data
console.log('Valid records found:', completeRecords.length);
} else {
console.log('No complete records available');
}

Safe Object Processing

const processUserData = userData => {
// Ensure we're working with a literal object
if (!isLiteralObject(userData)) {
throw new Error('Invalid user data format');
}

// Check if object has meaningful data
if (IsEmpty(userData)) {
return null; // No data to process
}

// Clean the data
const cleanData = removeFalsy(userData);

return cleanData;
};

Performance Considerations

  • Object Operations: O(n) where n is the number of properties
  • Array Operations: O(n) where n is the array length
  • Nested Object Operations: O(n*m) where n is array length and m is average object properties
  • Type Checking: O(1) - constant time operations

Error Handling

All utilities in this module handle edge cases gracefully:

  • Null/Undefined Inputs: Return empty objects/arrays or false
  • Invalid Types: Safely handle non-object/non-array inputs
  • Nested Data: Safely access nested properties without errors
  • Empty Collections: Properly handle empty objects and arrays


TypeScript Definitions

export function removeFalsy(obj: Record<string, any>): Record<string, any>;
export function removeFalsyFromArray(array: any[]): any[];
export function removeFalsyObjectFromArray(
array: Record<string, any>[],
): Record<string, any>[];
export function IsEmpty(values: Record<string, any>): boolean;
export function IsEmptyArray(arr: any[]): boolean;
export function isLiteralObject(param: any): boolean;
export function v2EmployeeOptionsList(
empArr: any[],
): Array<{ value: any; label: string; employee: any }>;
export function extractValuesByKeys(
sourceObject: Record<string, any>,
keys: string[],
): Record<string, any>;