Skip to content

Difference between two Objects – reduce

I’ve 2 Objects with data that is repeated but also varies. How to compare them and get the differences?

const obj1 = {
  surname: "kowalski",
  name: "adam",
  age: 23,
  city: "Wroclaw",
  country: "Poland",
};

const obj2 = {
  name: "adam",
  age: 34,
  city: "Warszawa",
  country: "Poland",
  friend: "Ala",
};

const objCombined = { ...obj1, ...obj2 };

I’ve to use .reduce.

My work:

const find = Object.entries(objCombined).reduce((diff, [key]) => {
  if (!obj2[key]) return diff;

  if (obj1[key] !== obj2[key]) diff[key] = obj2[key];

  return diff;
}, {});

but the output is without surname: "kowalski". Expected output:

{surname: "kowalski", age: 34, city: "Warszawa", friend: "Ala"}

Answer

Please use this code

const find = Object.entries(objCombined).reduce((diff, [key]) => {
  if (!obj2[key]) {
    diff[key] = obj1[key];
    return diff;
  }

  if (obj1[key] !== obj2[key]) diff[key] = obj2[key];

  return diff;
}, {});