Coding Challenge Practice - Question 81
Source: Dev.to
Task
Implement a function that replaces undefined values with null throughout a given input, handling primitives, arrays, and objects recursively.
Approach
- Base case – If the argument is exactly
undefined, returnnull. - Arrays – Detect with
Array.isArray. Create a new array of the same length, recursively process each element, and return the new array. - Objects – For non‑null objects, create a new empty object, iterate over its own enumerable keys, recursively process each value, and assign the result back to the corresponding key.
- Other values – Return the argument unchanged.
Implementation
function undefinedToNull(arg) {
// Replace undefined with null
if (arg === undefined) return null;
// Handle arrays
if (Array.isArray(arg)) {
const result = new Array(arg.length);
for (let i = 0; i < arg.length; i++) {
result[i] = undefinedToNull(arg[i]);
}
return result;
}
// Handle objects (excluding null)
if (arg !== null && typeof arg === 'object') {
const result = {};
for (const key in arg) {
if (Object.prototype.hasOwnProperty.call(arg, key)) {
result[key] = undefinedToNull(arg[key]);
}
}
return result;
}
// Primitive values (including null) are returned as‑is
return arg;
}