Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Determine how many key values have changed in an object

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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/lodash@4.17.21/lodash.min.js"></script>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading