Preface: How to judge whether two objects are equal?

Two objects of type Object are not considered equal when they are compared using == or ===, even if they have the same properties and values. This is because they are compared by reference (location in memory), unlike primitive types, which are compared by value.

var obj1 = {
    name: "xiaoming",
    sex : "male"
}
 
var obj2 = {
    name: "xiaoming",
    sex : "male"
}
 
console.log(obj1 === obj2); // false
Copy the code

But if the shallow copy points to the same memory, then the two objects are equal.

var obj1 = {
    name: "xiaoming",
    sex : "male"
};
 
var obj2 = {
    name: "xiaoming",
    sex : "male"
};
 
var obj3 = obj1;
 
console.log(obj1 === obj3); // true
 
console.log(obj2 === obj3); // false

Copy the code

As you can see, to check the “value equality” of an object, we basically iterate over every property of the object to see if they’re equal

/* * @param x {Object} Object 1 * @param y {Object} Object 2 * @return {Boolean} true */ export const deepEqual = (x, y) => {if (x === y) {return true; } else if ((typeof x == "object" && x ! = null) && (typeof y == "object" && y ! = null)) { if (Object.keys(x).length ! == Object.keys(y).length) { return false; } for (var prop in x) { if (y.hasOwnProperty(prop)) { if (! deepEqual(x[prop], y[prop])) return false; } else { return false; } } return true; } else { return false; }}Copy the code

Although this simple implementation applies to our example, there are many cases where it is not handled. Such as:

  1. What if one of the property values is itself an object?
  2. If one of the attribute values is NaN (in JavaScript, is that equal to its own unique value?)
  3. If the value of an attribute is undefined and the other object does not have this attribute (thus the result is uncertain?)

Conclusion:

A powerful way to check the “equality” of objects, preferably by relying on a well-developed library of tests, covers a variety of boundary cases. Underscore and LO-dash have a method called _.isequal () that better handles comparisons of deep objects.

Underscore () Underscore () : github.com/hanzichi/un…

Thank you for reading, I hope this article is helpful to you, if there are any deficiencies above, welcome to comment on the comments!!