Question 11

Question

How would you determine if two objects are structurally equal (e.g., object shapes)?

Answer

Determining structural equality means checking if two objects have the same properties and values, regardless of their order or nesting depth.

Here's a function to achieve that:

function areStructurallyEqual(obj1, obj2) {
  // Handle cases where one or both objects are not plain objects
  if (typeof obj1 !== 'object' || typeof obj2 !== 'object') {
    return obj1 === obj2; // Primitive values should be compared directly
  }

  // Check if both objects have the same number of properties
  const keys1 = Object.keys(obj1);
  const keys2 = Object.keys(obj2);
  if (keys1.length !== keys2.length) {
    return false; 
  }

  // Compare property values recursively
  for (let i = 0; i < keys1.length; i++) {
    const key = keys1[i];
    if (!areStructurallyEqual(obj1[key], obj2[key])) {
      return false; // Mismatch found in a nested property
    }
  }

  return true; 
}

// Example usage:
const objA = { a: 1, b: { c: 2 } };
const objB = { a: 1, b: { c: 2 } };
const objC = { a: 1, b: 3 }; // Different value in property 'b'

console.log(areStructurallyEqual(objA, objB)); // true
console.log(areStructurallyEqual(objA, objC)); // false

Explanation:

  1. Base Case: If either input isn't an object, we directly compare their values (since primitives are compared by value). 2. Property Counts: We ensure both objects have the same number of properties using Object.keys(). 3. Recursive Comparison:

    • For each matching property key:

      • Recursively call areStructurallyEqual() to compare nested objects.

      • If any recursive comparison returns false, we know they're not structurally equal, so return false.

  2. Structural Equality: Only if all property comparisons succeed, do we return true, indicating structural equality.

Last updated