Here's a clearer explanation of the undefinedToNull function with test cases.
β Implementation
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; }
Explanation:
- Check if the input is an object :
- If
objis not an object or isnull, it returns the input unchanged.
- Handle Arrays :
- If
objis an array (Array.isArray(obj)), it recursively callsundefinedToNullon each element of the array usingmap.
- Handle Objects :
- For an object, the function creates a new object (
result), iterates through the object properties, and recursively callsundefinedToNullon each property to handle potential nested structures.
- Recursive Call :
- The function handles any level of nesting (arrays within objects and objects within arrays).
Test Cases:
// 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.
Key Features:
- Recursion : Handles deeply nested arrays and objects.
- Handles
undefinedvalues : Replacesundefinedvalues withnull, while leaving other values intact. - Preserves object structure : The function maintains the same structure (arrays within objects, objects within arrays).
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.
Quick Quiz
Test your understanding with 3 quick questions
Q1What does `undefinedToNull({ a: undefined, b: 2 })` return?
Q2How does the function handle nested arrays containing undefined?
Q3Why is it useful to convert undefined to null?