Undefined to Null Problem
Description
LeetCode Problem 2775.
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.
Example 1:
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:
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:
objis a valid JSON object or array2 <= JSON.stringify(obj).length <= 10^5
Solution
Approach: Depth-first in-place rewrite
Walk the structure depth-first and fix it in place. For each key (or index) of the current object or array, first look at the value: if it is undefined, store null; if it is itself an object or array (and not null), recurse into it. for...in visits array indices as well as object keys, including slots that hold undefined.
typeof null is "object", so a real null must be skipped before recursing; the recursion would be harmless but the explicit check keeps the intent clear.
Complexity: Time O(n) over the number of values, space O(d) recursion depth.
/**
* @param {Object|Array} obj
* @return {Object|Array}
*/
var undefinedToNull = function (obj) {
for (const key in obj) {
if (obj[key] === undefined) {
obj[key] = null;
} else if (obj[key] !== null && typeof obj[key] === 'object') {
undefinedToNull(obj[key]);
}
}
return obj;
};