Object.keys()
This method involves comparing the keys of two objects directly.
Example: To demonstrate comparing the JavaScript object using the Object.keys() method in JavaScript.
const obj1 = { a: 1, b: 2 };
const obj2 = { b: 2, a: 1 };
const keys1 = Object
.keys(obj1)
.sort();
const keys2 = Object
.keys(obj2)
.sort();
console.log(JSON.stringify(keys1) === JSON.stringify(keys2));
Output
true
How to Compare Objects in JavaScript?
In JavaScript, comparing objects is not as simple as comparing numbers or strings. Objects are compared based on their memory references, so even if two objects have the same properties and values, they are considered distinct if they are stored in different memory locations.
Below are the various approaches to compare objects in JavaScript:
Table of Content
- Equality (===)
- JSON.stringify()
- Lodash Library
- Object.entries()
- Object.keys()