DEV Community

Discussion on: Comparing Values of Objects in JavaScript šŸ§­

Collapse
 
devdufutur profile image
Rudy NappƩe

You can't trust json stringify to compare objects... Stringified { a: 1, b: 2 } will be different than { b: 2, a: 1 } which isn't what you want.

Tuple and records will allow you to do that the simplest way. Check this proposal and it's polyfill : github.com/tc39/proposal-record-tuple

Collapse
 
nemo011 profile image
Nemo

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

Okay! I'll keep it in mind. Thanks. šŸ˜Š