Reputation: 75
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?
Upvotes: 7
Views: 19388
Reputation: 1
const changes = _.omitBy(
_.fromPairs(_.differenceWith(_.toPairs(obj1), _.toPairs(obj2), _.isEqual)),
_.isNil,
);
if (!_.isEmpty(changes)) {
....
}
Upvotes: 0
Reputation: 533
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 ] ]
Upvotes: 0
Reputation: 227
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.
Upvotes: 0
Reputation: 913
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>
Upvotes: 20