Undefined to Null - Problem
Given a deeply nested object or array obj, return the object obj with any undefined values replaced by null.
Why this matters: 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.
Note: The function should handle arbitrarily deep nesting of objects and arrays.
Input & Output
Example 1 — Basic Object
$
Input:
obj = {"a": 1, "b": null, "c": undefined}
›
Output:
{"a": 1, "b": null, "c": null}
💡 Note:
The undefined value at key 'c' is replaced with null. The existing null value at key 'b' remains unchanged.
Example 2 — Nested Array
$
Input:
obj = [1, undefined, [2, undefined, 3]]
›
Output:
[1, null, [2, null, 3]]
💡 Note:
Both undefined values are replaced with null - one at index 1 of outer array and one at index 1 of inner array.
Example 3 — Mixed Nesting
$
Input:
obj = {"arr": [undefined, {"nested": undefined}]}
›
Output:
{"arr": [null, {"nested": null}]}
💡 Note:
All undefined values are replaced regardless of nesting depth - in the array element and in the nested object property.
Constraints
- The input can be any valid JavaScript value
- Objects can be nested to arbitrary depth
- Arrays can contain mixed types including objects
- undefined values can appear at any nesting level
Visualization
Tap to expand
Understanding the Visualization
1
Input
Nested object/array with undefined values
2
Process
Recursively find and replace undefined with null
3
Output
Clean structure with null values
Key Takeaway
🎯 Key Insight: Recursively traverse nested structures and replace undefined with null to ensure safe JSON serialization
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code