Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

163
Views
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"}
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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;
}, {});
about 4 years ago · Juan Pablo Isaza Report

0

Remove if (!obj2[key]) return diff and add obj1[key]; if obj2[key]; is undefined:

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

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

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

  return diff;
}, {});

console.log(find);

about 4 years ago · Juan Pablo Isaza Report

0

We can use Object.keys() and Array.reduce() to get the difference between the two objects:

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 diff = [...Object.keys(obj1), ...Object.keys(obj2)].reduce((acc, key) => { 
    if (obj1[key] !== obj2[key]) {
       acc[key] = obj2[key] || obj1[key];
    }
    return acc;
}, {})

console.log("Diff:", diff);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!