Reputation: 2695
I have an array of object which looks like,
let givenobject = [{
a: "10",
b: "20"
}, {a: "30", b: "40"}, {a: "50", b: "60"}]
Now, I have one observable
which is
@observable values = {}
Now, On click a function gets triggerd which will assign this array of object to the observable.
setAction(givenobject) {
//Here I am trying to check wheather the coming object is same as that of previous(which is the observable) if both are same then do not update or else update.
if(givenobject !== values)
this. values = givenobject
}
SO, Can any one help me with this lodash function ?
Upvotes: 0
Views: 83
Reputation: 240
You can try this code, this will work with deep objects as well.
const compareArrObjects = _.isEmpty(_.differenceWith(givenobject , values , _.isEqual))
setAction(givenobject) {
//Here I am trying to check wheather the coming object is same as that of previous(which is the observable) if both are same then do not update or else update.
if(compareArrObjects)
this. values = givenobject
}
Upvotes: 0
Reputation: 21658
Here is my object compare function
const compare = (obj1, obj2) =>
Array.isArray(obj1)
? Array.isArray(obj2) && obj1.length === obj2.length && obj1.every((item, index) => compare(item, obj2[index]))
: obj1 instanceof Date
? obj2 instanceof Date && obj1.getDate() === obj2.getDate()
: obj1 && typeof obj1 === 'object'
? obj2 && typeof obj2 === 'object' &&
Object.getOwnPropertyNames(obj1).length === Object.getOwnPropertyNames(obj2).length &&
Object.getOwnPropertyNames(obj1).every(prop => compare(obj1[prop], obj2[prop]))
: obj1 === obj2;
const obj1 = [{
a: "10",
b: "20"
}, {a: "30", b: "40"}, {a: "50", b: "60"}];
const obj2 = [{
a: "10",
b: "20"
}, {a: "30", b: "40"}, {a: "50", b: "60"}]
const obj3 = [{
a: "10"
}, {a: "30", b: "40"}];
console.log('obj1 equals obj2 is', compare(obj1, obj2));
console.log('obj1 equals obj3 is', compare(obj1, obj3));
It is not good practice to use JSON.stringify to compare objects
Upvotes: 0
Reputation: 6373
With Lodash https://lodash.com/docs/4.17.15#isEqual
var object = { 'a': 1 };
var other = { 'a': 1 };
_.isEqual(object, other);
// => true
object === other;
// => false
Without: var isEqual = JSON.stringify(object1) == JSON.stringify(object2)
Upvotes: 1