DEV Community

loading...

Discussion on: Comparing Values of Objects in JavaScript 🧭

Collapse
nemo011 profile image
Nemo Author

Thanks for correcting me. Will definitely check and update the article. 😊

Collapse
devdufutur profile image
Rudy Nappée

You can do something like that if you want a generic function :

function areEquals(o1, o2) {
  if (!o1 || !o2) {
    return false;
  }
  return Object.keys(o1).length === Object.keys(o2).length 
    && Object.entries(o1).every(([key, value]) => {
      return key in o2 && o2[key] === value;
    });
}

console.log(areEquals({a: 1, b: 2}, {b: 2, a: 1})); // true
console.log(areEquals({a: 1}, {b: 2, a: 1})); // false
console.log(areEquals({a: 2}, {a: 1})); // false

If you wan't to go deeper and compare values in nested objects you can do :

function areDeepEquals(o1, o2) {
  if (!o1 || !o2) {
    return false;
  }
  return Object.keys(o1).length === Object.keys(o2).length 
    && Object.entries(o1).every(([key, value]) => {
      if (typeof value === "object") {
        return areDeepEquals(value, o2[key]);
      }
      return key in o2 && o2[key] === value;
    });
}

console.log(areDeepEquals({a: 1, b: 2, c: {d: 1}}, {b: 2, a: 1, c: {d: 1}})); // true
console.log(areDeepEquals({a: 1, b: 2, c: {d: 1}}, {b: 2, a: 1, c: {e: 1}})); // false
console.log(areDeepEquals({a: 1, b: 2, c: {d: 1}}, {b: 2, a: 1, c: {d: 2}})); // false
Thread Thread
devdufutur profile image
Rudy Nappée

Or you can use lodash isEqual() function !

Thread Thread
nemo011 profile image
Nemo Author

Okay! I'll keep it in mind. Thanks. 😊