Question 11
Question
Answer
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)); // falseLast updated