Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lodash Difference between two objects

I am comparing two objects with the help of Lodash isEqual function and trying to get difference with difference function.

The difference function is returning whole object instead of only those attributes which are different.

Is there any way to find only mismatched attributes in objects?

like image 980
Anmol Zahra Avatar asked Jun 07 '26 09:06

Anmol Zahra


1 Answers

const obj1 = {
  a: "old value",
  b: {
    c: "old value"
  },
  d: 123
}
const obj2 = {
  a: "old value",
  b: {
    c: "new value"
  },
  d: 321
}
const changes =
  _.differenceWith(_.toPairs(obj2), _.toPairs(obj1), _.isEqual)

// Changes in array form
console.log(changes)
// Changes in object form
console.log(_.fromPairs(changes))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
like image 54
Dani Avatar answered Jun 09 '26 00:06

Dani