We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Undefined to Null

Number: 2781

Difficulty: Medium

Paid? Yes

Companies: N/A


Problem Description

Given a deeply nested object or array, the task is to traverse the entire structure and replace any occurrence of the undefined value with null. This ensures that when converting the object to JSON (using JSON.stringify), no unexpected omissions occur because undefined values are handled differently.


Key Insights

  • The problem requires a complete traversal of a nested data structure which can contain objects and arrays.
  • A recursive approach is well-suited because of the unknown depth and mixed types (objects and arrays).
  • It's important to differentiate between undefined values and null values, and only replace undefined.
  • Edge cases include handling nested arrays, objects, and mixed types.
  • The input is assumed to be valid JSON object or array.

Space and Time Complexity

Time Complexity: O(n), where n is the total number of elements (properties and array items) in the structure. Space Complexity: O(n) in the worst-case scenario due to recursion stack and auxiliary space used for traversal.


Solution

The solution uses recursion to traverse the nested structure. It checks the type of the current element:

  • If it is an object, iterate over its own keys. For each property, if its value is undefined, set it to null; if it is an object or array, recursively process it.
  • If it is an array, loop through each item and perform similar checks as with objects.
  • Direct values other than objects, arrays, or undefined are returned without modifications. This recursive traversal ensures that all nested occurrences of undefined are replaced with null.

Code Solutions

# Define a function to convert undefined to null.
# In Python, we simulate undefined with a unique value, but since Python doesn't have "undefined",
# we'll assume the data is given in a format where 'None' represents null and a custom marker like "UNDEFINED"
# is used to represent undefined. In actual JavaScript, native undefined values would be processed.
def convert_undefined_to_null(obj):
    # Check if obj is a list; if so, process each element.
    if isinstance(obj, list):
        # Iterate through each index of the list.
        for i in range(len(obj)):
            # If the element is the undefined placeholder, replace it with None.
            if obj[i] == "UNDEFINED":
                obj[i] = None
            # If the element is a dict or list, process it recursively.
            elif isinstance(obj[i], (dict, list)):
                convert_undefined_to_null(obj[i])
    elif isinstance(obj, dict):
        # Iterate through all keys in the dictionary.
        for key in list(obj.keys()):
            # If the value is the undefined placeholder, set it as None.
            if obj[key] == "UNDEFINED":
                obj[key] = None
            # If the value is a dict or list, process it recursively.
            elif isinstance(obj[key], (dict, list)):
                convert_undefined_to_null(obj[key])
    # Return the modified object.
    return obj

# Example usage:
data = {"a": "UNDEFINED", "b": [ "a", "UNDEFINED" ]}
print(convert_undefined_to_null(data))
← Back to All Questions