Object equals object javascript

check object Equal object javascript [duplicate]

The following object types are compared by value, not by reference:

Additionally, there’s one object which is never equal to itself, not even by reference:

var test = NaN; alert ( test == NaN ); // false alert ( test == test ); // false (!) 

To check whether two objects are equal, you have to define equality:

  • «Two objects are equal if they contain the same property names and values»
    Which implies that object A has to have the same number of properties as object B, and that every property in A has also to be a property of B.

@user1194313, no, your question was «why doesn’t this work?» which you didn’t even take the time to write out correctly. Asking for code without putting any effort in is rude and unacceptable behavior.

If you want code, there are plenty of duplicate questions. I posted this answer, because it seemed that you want to know when objects are equal. I have never seen anyone mentioning NaN in an answer to this question, so I wanted to create one. @user1194313 If you reduce this question to «Give meh teh codez to compare objects», I will vote to close this question as a duplicate (no offence intended).

@RobW I believe you mean the term «value». The term «object» is already defined in the spec to mean «a member of the Object type» — see here. A 5 is defined as a value (of the Number type).

@amnotiam By that they mean that arrays, functions, regular expressions, etc. are objects. I wouldn’t use that definition, since it’s ambiguous when placed out of context.

I guess I’m just not sure it’s helpful to call them objects even though JavaScript will convert them to their object type for you. Take this sentence «The following object types are compared by value, not by reference: *Strings. « Given that, it would seem that the following should be true. s1 = new String(«foo»); s2 = new String(«foo»); s1 == s2; . but it isn’t. Just seems like the distinction is important.

Источник

How to Compare Objects in JavaScript

In JavaScript, objets are always stored by reference. That means one object is strictly equal another only if they both point to the same object in memory.

const o1 = < answer: 42 >; const o2 = o1; const o3 = < answer: 42 >; o1 === o2; // true, same reference o1 === o3; // false, different reference but same keys and values

However, what if you want to check whether two POJOs have the same data? In other words, the same keys and values? Here’s 3 possible approaches.

Читайте также:  Направления программирования для python

Keys and Values Shallow Equal

One simple approach is to iterate through each key and value in the two objects and check if the keys and values are strictly equal.

const o1 = < question: null, answer: 42 >; const o2 = < question: null, answer: 42 >; objectsEqual(o1, o2); // true objectsEqual(o1, < answer: 43 >); // false function objectsEqual(o1, o2) < const entries1 = Object.entries(o1); const entries2 = Object.entries(o2); if (entries1.length !== entries2.length) < return false; > for (let i = 0; i < entries1.length; ++i) < // Keys if (entries1[i][0] !== entries2[i][0]) < return false; > // Values if (entries1[i][1] !== entries2[i][1]) < return false; > > return true; >

Deep Equality using JSON.stringify()

The previous section shows how to compare objects by checking if the two objects’ keys and values are strictly equal. But what if one of the values is an object?

const o1 = < name: < first: 'Arthur', lastName: 'Dent' >, planet: 'Earth' >; const o2 = < name: < first: 'Arthur', lastName: 'Dent' >, planet: 'Earth' >; objectsEqual(o1, o2); // false, because `o1.name !== o2.name`

You can make objectsEqual() recursive, but then you need to be careful about infinite recursion. An easy way to compare whether two POJOs are deeply equal is comparing their JSON representations using JSON.stringify() :

const o1 = < name: < first: 'Arthur', lastName: 'Dent' >, planet: 'Earth' >; const o2 = < name: < first: 'Arthur', lastName: 'Dent' >, planet: 'Earth' >; JSON.stringify(o1) === JSON.stringify(o2); // true delete o2.planet; JSON.stringify(o1) === JSON.stringify(o2); // false

The JSON.stringify() function comes with a few limitations that make it a lackluster choice for checking deep equality. First, key order matters:

const o1 = < question: null, answer: 42 >; const o2 = < answer: 42, question: null >; JSON.stringify(o1) === JSON.stringify(o2); // false

Second, not all types are representable in JSON. The JSON.stringify() function converts dates to strings, and ignores keys whose value is undefined , which can lead to surprising results.

const o1 = < myDate: new Date('2016-06-01'), otherProperty: undefined >; const o2 = < myDate: '2016-01-01T00:00:00.000Z' >; JSON.stringify(o1) === JSON.stringify(o2); // true

Using Lodash’s isEqual()

Lodash’s isEqual() function is the most sophisticated way to compare two objects. It handles a wide variety of edge cases and avoids a lot of the pitfalls of the previous two approaches.

const obj1 = < date: new Date('2020/06/01'), num: new Number(1) >; const obj2 = < date: new Date('2020/06/01'), num: 1 >; _.isEqual(obj1, obj2); // true
const obj1 = < name: 'Will Riker', rank: 'Commander' >; class Character <> const obj2 = new Character(); Object.assign(obj2, < name: 'Will Riker', rank: 'Commander' >); _.isEqual(obj1, obj2); // false

The isEqual() function is also smart enough to avoid infinite recursion.

const obj1 = <>; const obj2 = <>; obj1.circular = obj1; obj2.circular = obj1; _.isEqual(obj1, obj2); // true

If you’re already using Lodash, isEqual() is the best approach to comparing if two objects are deep equal. The shallow strict comparison approach is good for cases where you aren’t worried about nested objects, and JSON.stringify() can help provide a rough deep equality check in cases where you can’t use Lodash. But, if you can use Lodash, isEqual() is the best approach for checking whether two objects are deeply equal.

Читайте также:  Concatenate two strings python

More Fundamentals Tutorials

Источник

JavaScript Comparison Operators – How to Compare Objects for Equality in JS

Dionysia Lemonaki

Dionysia Lemonaki

JavaScript Comparison Operators – How to Compare Objects for Equality in JS

While coding in JavaScript, there may be times when you need to compare objects for equality. The thing is, comparing objects in JavaScript is not that straightforward.

In this article, you learn three ways to compare objects for equality in JavaScript.

What’s the Difference Between Comparing Primitive Data Types VS Non-Primitive Data Types in JavaScript?

Data types in JavaScript fall into one of two categories:

  • Primitive (such as Number, String, Boolean, Undefined, Null, Symbol)
  • Non-primitive (such as Object)

Primitive data types refer to a single value, and comparing primitive values is relatively straightforward – you only need to use any of the comparison operators.

In the following example, I use the strict equality operator, === , which checks if the two operands are equal and returns a Boolean as a result:

let a = 1; let b = 1; console.log(a === b); // true 

You can also assign the value of the variable a to another variable, a1 , and compare them:

let a = 1; let b = 1; let a1 = a; console.log(a === a1); // true 

In the example above, both variables point to the same value, so the result is true .

When it comes to objects, however, comparing them isn’t that straightforward.

let a = < name: 'Dionysia', age: 29>; let b = ; console.log(a === b); // false 

Even though both objects have the same key and value pairs, the result of the comparison is false . Why is that?

Is it because I used the strict equality operator, === ? What happens if I use the loose quality operator, == ?

let a = < name: 'Dionysia', age: 29>; let b = ; console.log(a == b); // false 

Both a and b are seemingly the same, yet the objects are not equal when I use === or == .

You would think that two objects with the same properties and properties with the same values would be considered equal.

The reason for this result has to do with how JavaScript approaches testing for equality when it comes to comparing primitive and non-primitive data types.

The difference between primitive and non-primitive data types is that:

  • primitive data types are compared by value.
  • non-primitive data types are compared by reference.

In the following sections, you will see some ways to compare objects for equality.

How to Compare Objects by Reference in JavaScript

As you saw from the example in the section above, using == and === returns false when you try to compare objects by value:

let a = < name: 'Dionysia', age: 29>; let b = ; console.log(a === b); // false 

Both objects have identical keys and values, but the result was false because they are different instances.

To compare objects by reference, you have to test whether both point to the same location in memory.

When referring to an object, you refer to an address in memory.

let a = < name: 'Dionysia', age: 29>; let b = a; console.log(a === b); // true 

In the example above, thanks to the line let b = a; , both variables have the same reference and point to the same object instance, so the result is true .

Читайте также:  Размеры изображения

When I assign the variable a to the b , the address of a gets copied to b . This results in both having the same address – not the same value.

With that said, most of the time, you will want to compare objects by value and not by instance.

And as you saw, you can’t just use == or === to compare objects by value – it requires a bit more work.

How to Compare Objects Using The JSON.stringify() Function in JavaScript

One way you can compare two objects by value is by using the JSON.stringify function.

The JSON.stringify() function converts objects into equivalent JSON strings. You can then use any of the comparison operators to compare the strings.

let a = < name: 'Dionysia', age: 29>; let b = < name: 'Dionysia', age: 29>; console.log(JSON.stringify(a) === JSON.stringify(b)); // true 

The JSON.stringify() function converted both objects into JSON strings, and since both a and b have the same properties and values, the result is true .

But JSON.stringify() isn’t always the best solution for comparing objects by value since it has limitations.

First of all, when using JSON.stringify() , the order of the keys matters.

Look at what happens when the keys are in a different order:

let a = < age: 29, name: 'Dionysia'>; let b = < name: 'Dionysia', age: 29>; console.log(JSON.stringify(a) === JSON.stringify(b)); //false 

In this example, you would expect the result to be true since the values are the same – only the order of the keys got reversed.

JSON.stringify() stringifies the object as it is, so the order of the keys is important. If they are not in the same order, the result will be false .

So, JSON.stringify() is not the best choice for comparing objects since you can’t always be certain of the order of the keys.

There is also an additional limitation: JSON doesn’t represent all types.

Look at what happens when the value of one key is undefined:

let a = < name: 'Dionysia'>; let b = < name: 'Dionysia', age: undefined>; console.log(JSON.stringify(a) === JSON.stringify(b)); //true 

In the example above, the result is unexpected. The result should have been false but returned as true because JSON ignores keys whose values are undefined.

How to Compare Objects Using the Lodash _.isEqual() Method in JavaScript

An elegant and sophisticated solution for comparing objects by their value is to use the well-tested JavaScript library Lodash and its _.isEqual() method.

Let’s take the example from the previous section, where the keys have the same value but are in a different order, and use the _.isEqual() method:

let a = < age: 29, name: 'Dionysia'>; let b = < name: 'Dionysia', age: 29>; console.log(_.isEqual(a, b)); // true 

In the previous section, the result when using JSON.stringify was false .

The Lodash library offers a variety of edge cases and performs a deep comparison between two values to check if the two objects are deeply equal.

Conclusion

In this article, you learned how to compare objects for equality in JavaScript.

You saw three different ways and the pros and cons of each. When in doubt, the most effective way to compare objects is by using the Lodash library.

Thank you for reading, and happy coding!

Источник

Оцените статью