6

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?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Anmol Zahra
  • 65
  • 1
  • 1
  • 4
  • 2
    [`_.difference()`](https://lodash.com/docs/#difference) is supposed to be used with arrays. – VLAZ Jun 15 '21 at 11:13
  • 1
    Relevant: [There's no such thing as a "JSON Object"](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/) and [What is the difference between JSON and Object Literal Notation?](https://stackoverflow.com/q/2904131) – VLAZ Jun 15 '21 at 11:17
  • 1
    Does this answer your question? [How to do a deep comparison between 2 objects with lodash?](https://stackoverflow.com/questions/31683075/how-to-do-a-deep-comparison-between-2-objects-with-lodash) – Hassan Imam Jun 15 '21 at 11:19

3 Answers3

15

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>
Dani
  • 824
  • 7
  • 12
0

I wanted to do the comparison between two objects but in my case, I wanted to check only some properties of the objects. So I use pick and isEqual from lodash.

const obj1 = {p1: 1, p2: 2, p3: 3};
const obj2 = {p1: 1, p2: 2, p3: 3};

const comparisonProperties = ["p1", "p2"];

console.log(_.isEqual(_.pick(obj1, comparisonProperties), _.pick(obj2, comparisonProperties))

This is how I did it.

CodeByAk
  • 139
  • 5
0

You can easily compare two objects without lodash

const obj1 = {
  one: 1,
  two: 2,
  three: 4,
  four: 3,
};

const obj2 = {
  one: 1,
  two: 2,
  three: 3,
  four: 4,
};

const diffInVariantFields = (obj1, obj2) => {
  const diffInFields = Object.entries(obj2).filter(
    ([field, obj2Value]) => obj1[field] !== obj2Value
  );
  return diffInFields;
};

console.log(diffInVariantFields(obj1, obj2)); // [ [ 'three', 3 ], [ 'four', 4 ] ]
Anil Kumar
  • 465
  • 4
  • 10