I have two of the same objects to compare, with different data types as object props (array and object).
I want to know how many properties are different than the first one. See example below:
OriginalObject = {
names : [],
numbers : [],
dates :{
from: null,
to : null,
},
other :{
from: null,
to : null,
},
}
ModifiedObject = {
names : ['Steven', 'Judy'],
numbers : [1,5,7],
dates :{
from: 15152112512,
to : null,
},
other :{
from: null,
to : null,
},
}
Since names, numbers, and dates changed, desired output is: 3
I was thinking perhaps I could iterate over the object properties and use _.isEqual of lodash, but I would like to know if there is an easy and shorthanded version to do achieve this.
CodePudding user response:
If you want a solution using lodash, you could apply _.toPairs()
on both of your objects. Then use _.differenceWith()
to compare the obtained arrays and finally get the length of the comparison array :
OriginalObject = {
names : [],
numbers : [],
dates :{
from: null,
to : null,
},
other :{
from: null,
to : null,
},
}
ModifiedObject = {
names : ['Steven', 'Judy'],
numbers : [1,5,7],
dates :{
from: 15152112512,
to : null,
},
other :{
from: null,
to : null,
},
}
console.log(_.differenceWith(_.toPairs(OriginalObject), _.toPairs(ModifiedObject), _.isEqual).length);
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
CodePudding user response:
I have used this as a solution.
appliedFiltersCount (state) {
let changedCount = 0
Object.keys(state.filters).forEach((field) => {
if (field in state.filters && field in getDefaultState().filters) {
if (!isEqual(state.filters[field], getDefaultState().filters[field])) {
changedCount
}
}
})
return changedCount
},