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

120
Views
JS Object compare and get diff only

I have 2 objects.

The one object is Original Data.

const origin = { name: 'John', id: 'Doe', item: { drink: 'coffee', money: 0 } }

And the other object is Copied and Edited Data

const copied = { name: 'Alex', id: 'Doe', item: { drink: 'water', money: 0 } }

I would like to compare them and get diff only.

const out = compareObj(origin, copied);
console.log(out)
/*
{ name: 'Alex', item: { drink: 'water' } }
*/

How can I get this?

Thanks in advance.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can recursively loop over the object and delete the non-duplicate properties from the copy object.

And if a property exists on the the original object and not on the copy, then add it into the copy object. Following part of the code does that:

if (!copy.hasOwnProperty(k)) {
  copy[k] = v;
}

function compare(original, copy) {
  for (let [k, v] of Object.entries(original)) {
    if (typeof v === "object" && v !== null) {
      if (!copy.hasOwnProperty(k)) {
        copy[k] = v;
      } else {
        compare(v, copy?.[k]);
      }
    } else {
      if (Object.is(v, copy?.[k])) {
        delete copy?.[k];
      }
    }
  }
  return copy;
}

const 
  original = { name: "John", id: "Doe", item: { drink: "coffee", money: 0, honey: 24 } },
  copy = { name: "Alex", id: "Doe", item: { drink: "water", money: 0 } },
  diff = compare(original, JSON.parse(JSON.stringify(copy)));

console.log(diff);

Note: You need to pass a clone of the copy object to the function since it mutates the passed copy object.

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!