Why can’t I compare an object to another object?

Asked

Viewed 86 times

2

I have the following very simple code

var x = new String("html");
var y = new String("html");

window.alert(x == y);

And he returns to me false Is it possible for me to compare two objects? And why can’t I compare two objects being that both are equal?

1 answer

4

Well objects are treated as reference, or memory pointer, so it is not possible to use === or == to compare the two. A quick way to compare the two objects is to see if they have the same value in the key. This can be done using JSON.stringify. Another way is to use the Lodash function isEqual.

const ob1 = {obj: 'A'};
const ob2 = {obj: 'A'};

// JavaScript
JSON.stringify(ob1) === JSON.stringify(ob2); // true

// Lodash
_.isEqual(ob1, ob2); // true

A note in case you choose to use JSON.stringify() keep in mind that the order of things (the key value pair) is important, so if they are not in the objects in the same order the result will be different.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.