Object Equality
checks two objects and outputs true if they are the same or false if they are different. Checks both keys and values.
by Oliver Kelso
JavaScript
var jangoFett = {
occupation: "Bounty Hunter",
genetics: "superb",
};
var bobaFett = {
occupation: "Bounty Hunter",
genetics: "superb"
};
function isEquivalent(a, b) {
diff = [];
// Create arrays of property names
var aProps = Object.getOwnPropertyNames(a);
var bProps = Object.getOwnPropertyNames(b);
// If number of properties is different,
// objects are not equivalent
if (aProps.length != bProps.length) {
diff['message'] = "Keys in objects do not match";
return this.diff;
}
for (var i = 0; i < aProps.length; i++) {
var propName = aProps[i];
// If values of same property are not equal,
// objects are not equivalent
if (a[propName] !== b[propName]) {
diff['mismatch'] = a[propName] + " - " + b[propName];
return diff;
}
}
// If we made it this far, objects
// are considered equivalent
return true;
}
console.log(isEquivalent(bobaFett, jangoFett));