0
const users = [
    {name:'John',age:24},
    {name:'Victor',age:28}
];

const newUser = JSON.parse(JSON.stringify(users));
console.log(users);
console.log(newUser);
console.log(typeof(users));
console.log(typeof(newUser));
console.log(users==newUser)

OUTPUT:

[ { name: 'John', age: 24 }, { name: 'Victor', age: 28 } ]
[ { name: 'John', age: 24 }, { name: 'Victor', age: 28 } ]
object
object
false

object users and newUser have exactly same items and values. They why users==newUser is false?

  • Does this answer your question? [Object comparison in JavaScript](https://stackoverflow.com/questions/1068834/object-comparison-in-javascript) – Bumhan Yu Feb 26 '22 at 03:52
  • In JavaScript, two objects aren't necessarily evaluated equal even if they share the same attributes and values. Refer to [this StackOverflow question](https://stackoverflow.com/questions/1068834/object-comparison-in-javascript/1144249#1144249). – Bumhan Yu Feb 26 '22 at 03:54
  • you can have 2 cars of the same brand/model/color..., they will always remain different cars, it's the same for objects – Mister Jojo Feb 26 '22 at 03:55

1 Answers1

0

In Javascript the equals operator compares object instances, not values. They are 2 different instances, so not equal.

One way to compare the values is to use a deep equals library. Another way is to compare the JSON.stringify value.

JSON.stringify(users) === JSON.stringify(newUser) // true

A caveat of the stringify approach is that undefined values are stripped.

Steven Spungin
  • 27,002
  • 5
  • 88
  • 78