Contact
Back to Home

Could you demonstrate how to build undefinedToNull(), converting undefined elements in an object to null?

Featured Answer

Question Analysis

The question asks you to create a function named undefinedToNull() that transforms an object's properties. Specifically, you need to convert any property with a value of undefined to null. This involves iterating over the object's properties and checking each value. If a property's value is undefined, it should be updated to null.

To solve this problem, you need to:

  • Traverse the object's properties.
  • Check if a property's value is undefined.
  • Replace undefined with null where applicable.

This question is testing your understanding of:

  • Object manipulation in JavaScript.
  • Iterating over objects.
  • Conditional logic for checking and updating values.

Answer

Here is a simple implementation of the undefinedToNull() function in JavaScript:

function undefinedToNull(obj) {
  // Check if the input is an object
  if (typeof obj !== 'object' || obj === null) {
    return obj;
  }

  // Iterate over each property of the object
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      // Check if the property value is undefined
      if (obj[key] === undefined) {
        // Convert undefined value to null
        obj[key] = null;
      }
    }
  }
  
  // Return the modified object
  return obj;
}

// Example usage:
let exampleObj = {
  a: 1,
  b: undefined,
  c: 'test',
  d: undefined
};

console.log(undefinedToNull(exampleObj));
// Output: { a: 1, b: null, c: 'test', d: null }

Explanation:

  • The function first checks if the input is an object and not null.
  • It then iterates over the object's properties using a for...in loop.
  • It ensures that the property belongs to the object by using hasOwnProperty().
  • For each property, if the value is undefined, it updates the value to null.
  • Finally, the modified object is returned.

This approach ensures that only properties with undefined values are transformed, while other properties remain unchanged.