Loading article...
Here's a clearer explanation of the undefinedToNull function with test cases.
function undefinedToNull(obj) { if (typeof obj !== 'object' || obj === null) { // If the input is not an object or is null, return it as is return obj; } // Handle arrays if (Array.isArray(obj)) { return obj.map(item => undefinedToNull(item)); // Recursively call on array items } // Handle objects const result = {}; for (const key in obj) { if (obj.hasOwnProperty(key)) { result[key] = undefinedToNull(obj[key]); // Recursively call on object properties } } return result; }
obj is not an object or is null, it returns the input unchanged.obj is an array (Array.isArray(obj)), it recursively calls undefinedToNull on each element of the array using map.result), iterates through the object properties, and recursively calls undefinedToNull on each property to handle potential nested structures.// Test case 1: Simple object with undefined values console.log(undefinedToNull({ a: undefined, b: 'BFE.dev' })); // Expected Output: { a: null, b: 'BFE.dev' } // Explanation: The `undefined` value is replaced with `null` in the resulting object. // Test case 2: Object with arrays containing undefined values console.log(undefinedToNull({ a: ['BFE.dev', undefined, 'bigfrontend.dev'] })); // Expected Output: { a: ['BFE.dev', null, 'bigfrontend.dev'] } // Explanation: The `undefined` in the array is replaced with `null`, while other values remain unchanged.
undefined values : Replaces undefined values with null, while leaving other values intact.This function is useful when you need to sanitize an object or array by replacing all undefined values with null, which can be particularly helpful for data processing or preparation.
Test your understanding with 3 quick questions