When working with JavaScript data structures, you'll often encounter undefined values that can cause issues during JSON serialization. Your task is to create a function that transforms any deeply nested object or array by replacing all undefined values with null.
Why does this matter? When you call JSON.stringify() on an object containing undefined values, those properties are completely omitted from the resulting JSON string. However, null values are preserved. This function ensures your serialized data maintains its structure and doesn't lose important properties.
Example: JSON.stringify({a: undefined, b: 5}) returns "{"b":5}", but JSON.stringify({a: null, b: 5}) returns "{"a":null,"b":5}".
The input can be arbitrarily nested with objects, arrays, primitive values, and undefined values at any level.
Input & Output
Constraints
-
The input
objcan be any valid JavaScript value - Maximum nesting depth is 1000 levels
- Objects can have up to 104 properties
- Arrays can have up to 104 elements
-
Only
undefinedvalues should be replaced, not other falsy values