Object.entries()
You can convert objects into arrays of key-value pairs and then compare them.
Example: To demonstrate comparing the JavaScript object using the Object.entries method.
function compareEntries(obj1, obj2) {
const entries1 = Object.entries(obj1);
const entries2 = Object.entries(obj2);
return JSON
.stringify(entries1) === JSON
.stringify(entries2);
}
const obj1 = { a: 1, b: 2 };
const obj2 = { a: 1, b: 2 };
console.log(compareEntries(obj1, obj2));
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()