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
Undefined to Null Conversion INPUT obj = { "a": 1 OK "b": null OK "c": undefined FIX } Problem: undefined breaks JSON Red = needs conversion Green = valid value ALGORITHM STEPS 1 Check Type Is value undefined? 2 Replace In-Place Set to null directly 3 Recurse Nested Process child objects 4 Return Object Modified in-place Conversion Process undefined null obj[key] = null JSON-safe now! FINAL RESULT result = { "a": 1 "b": null "c": null } OK JSON-safe object! JSON.stringify() {"a":1,"b":null,"c":null} Key Insight: In-Place Modification means we directly modify the original object without creating a new copy. JSON.stringify() silently drops undefined values, causing data loss. Converting to null preserves keys! TutorialsPoint - Undefined to Null | In-Place Modification Approach
Asked in
Google 25 Facebook 20 Amazon 15
23.4K Views
Medium Frequency
~15 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen