Removing Undefined Values from an Object - dialloi659/angular GitHub Wiki

cleanObject Function

The cleanObject function cleans an object by removing properties with undefined values. Specifically, it removes properties that have a value of undefined, null, NaN, "", or " ".

Usage

/**
 * Cleans an object by removing properties with undefined values.
 * Specifically, it removes properties that have a value of undefined, null, NaN, "", or " ".
 *
 * @param obj - The input object to be cleaned.
 * @returns A new object with undefined values removed.
 *
 * @example
 * const obj = {
 *     a: undefined,
 *     b: null,
 *     c: NaN,
 *     d: "",
 *     e: " ",
 *     f: "validValue",
 *     g: 123,
 * };
 * const cleanedObj = cleanObject(obj);
 * console.log(cleanedObj); // Outputs: { f: "validValue", g: 123 }
 */
export const cleanObject = <T extends Record<string, any>>(obj: T): T =>  {
  const result: Partial<T> = {};

  for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
          const value = obj[key];
          if (
              value !== undefined &&
              value !== null &&
              value !== "" &&
              value !== " " &&
              !Number.isNaN(value)
          ) {
              result[key] = value;
          }
      }
  }

  return result as T;
}

Signature

cleanObject<T extends Record<string, any>>(obj: T): T
  • obj: The input object to be cleaned.

Returns

A new object with undefined values removed.

Examples

const obj = {
    a: undefined,
    b: null,
    c: NaN,
    d: "",
    e: " ",
    f: "validValue",
    g: 123,
};

const cleanedObj = cleanObject(obj);
console.log(cleanedObj); // Outputs: { f: "validValue", g: 123 }

Remarks

  • Properties of the input object that have values of undefined, null, NaN, "", or " " will be removed from the returned object.
  • Properties with numeric values (other than NaN) or non-empty string values will be retained.
  • Properties with unsupported values such as nested objects or functions are not cleaned.