nested object replace all undefined values with null in typescript

You can achieve this using the recursive function. Here's an example implementation:

index.ts
function replaceUndefinedWithNull(obj: {[key: string]: any }): {[key: string]: any } {
  const result: {[key: string]: any } = {};
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      const value = obj[key];
      if (value === undefined) {
        result[key] = null;
      } else if (typeof value === 'object') {
        result[key] = replaceUndefinedWithNull(value);
      } else {
        result[key] = value;
      }
    }
  }
  return result;
}
466 chars
17 lines

This function takes an object as the input and returns a new object where all undefined values are replaced with null. It recursively loops through all properties of the object and if a property is undefined, it replaces it with null. If the property is an object, it recursively calls the function with that object as the input. If the property is not an object or undefined, it copies the value to the new object.

Here's an example usage:

index.ts
const obj = {
  prop1: undefined,
  prop2: 'value',
  prop3: {
    nestedProp1: undefined,
    nestedProp2: 'nestedValue'
  }
};

const newObj = replaceUndefinedWithNull(obj);
console.log(newObj);
// Output: { prop1: null, prop2: 'value', prop3: { nestedProp1: null, nestedProp2: 'nestedValue' } }
298 chars
13 lines

This will output a new object where all undefined values are replaced with null.

gistlibby LogSnag