Skip to main content
Back to problems
#2775
Medium JavaScript

Undefined to null

72.0% acceptance
Mar 31, 2026
15
1
Given a deeply nested object or array obj, return the object obj with any undefined values replaced by null. undefined values are handled differently than null values when objects are converted to a JSON string using JSON.stringify(). This function helps ensure serialized data is free of unexpected errors.

Solution

TypeScript
Time O(n)
Space O(1)
LeetCode
solution.ts
type JSONValue =
  | null
  | boolean
  | number
  | string
  | JSONValue[]
  | { [key: string]: JSONValue };
type Value =
  | undefined
  | null
  | boolean
  | number
  | string
  | Value[]
  | { [key: string]: Value };

type Obj1 = Record<string, Value> | Array<Value>;
type Obj2 = Record<string, JSONValue> | Array<JSONValue>;

function undefinedToNull(obj: Obj1): Obj2 {
  for (const key in obj) {
  if ((obj as any)[key] === undefined) {
    (obj as any)[key] = null;
  } else if (
    typeof (obj as any)[key] === "object" &&
    (obj as any)[key] !== null
  ) {
    undefinedToNull((obj as any)[key]);
  }
  }
  return obj as Obj2;
}

/**
 * undefinedToNull({"a": undefined, "b": 3}) // {"a": null, "b": 3}
 * undefinedToNull([undefined, undefined]) // [null, null]
 */