Problem

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.

Examples

Example 1:

1
2
3
Input: obj = {"a": undefined, "b": 3}
Output: {"a": null, "b": 3}
Explanation: The value for obj.a has been changed from undefined to null

Example 2:

1
2
3
Input: obj = {"a": undefined, "b": ["a", undefined]}
Output: {"a": null,"b": ["a", null]}
Explanation: The values for obj.a and obj.b[1] have been changed from undefined to null

Constraints:

  • obj is a valid JSON object or array
  • 2 <= JSON.stringify(obj).length <= 10^5

Solution

Method 1 – Recursion and Type Checking

Intuition

Recursively traverse the object or array, replacing any undefined value with null. For objects, process each key; for arrays, process each element.

Approach

  1. If the value is undefined, return null.
  2. If the value is an array, recursively process each element.
  3. If the value is an object, recursively process each property.
  4. Otherwise, return the value as is.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
function undefinedToNull(obj: any): any {
    if (obj === undefined) return null;
    if (Array.isArray(obj)) return obj.map(undefinedToNull);
    if (obj !== null && typeof obj === 'object') {
        const res: any = {};
        for (const k in obj) {
            if (Object.prototype.hasOwnProperty.call(obj, k)) {
                res[k] = undefinedToNull(obj[k]);
            }
        }
        return res;
    }
    return obj;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
function undefinedToNull(obj) {
    if (obj === undefined) return null;
    if (Array.isArray(obj)) return obj.map(undefinedToNull);
    if (obj !== null && typeof obj === 'object') {
        const res = {};
        for (const k in obj) {
            if (Object.prototype.hasOwnProperty.call(obj, k)) {
                res[k] = undefinedToNull(obj[k]);
            }
        }
        return res;
    }
    return obj;
}

Complexity

  • ⏰ Time complexity: O(n) — Each value is visited once.
  • 🧺 Space complexity: O(n) — For recursion stack and output object.