Skip to content
Advertisement

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"}

Advertisement

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;
}, {});
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement