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

How to compare two objects but skip values and just compare keys and key types?

I want to write unit testing using Jest for my Node.js functions and need to test if response object has some specific keys or not. Something like this:

expect(await mokChannelsService.getChannel(inputDto)).toEqualKeys(outputDto);

// Or just a normal function

const result = await mokChannelsService.getChannel(inputDto);
const equal = toEqualKeys(result, outputDto);

This toEqualKeys function should check equality just for keys not values. And these objects are not instances of a class. for example these two objects should be equal:

const object1 = {
  names: {
    firstName: '',
    lastName: '',
  },
  phone: 1,
};

const object2 = {
  names: {
    firstName: 'John',
    lastName: 'Due',
  },
  phone: 1234567890,
};

const object3 = {
  names: {
    firstName: 'John',
    lastName: 12,
  },
  mobile: '12345',
};

const result1 = toEqualKeys(object1, object2); // true
const result1 = toEqualKeys(object1, object3); // false

Is there any NPM packages available for this?

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

>Solution :

You can iterate each of the keys in object1, checking that the same key exists in object2 and – if the associated property in object1 is an object, that all the keys from that object also exist in a similar object in object2:

const object1 = {
  names: {
    firstName: '',
    lastName: '',
  },
  phone: 1,
};

const object2 = {
  names: {
    firstName: 'John',
    lastName: 'Due',
  },
  phone: 1234567890,
};

const object3 = {
  names: {
    firstName: 'John',
    lastName: 12,
  },
  mobile: '12345',
};

const toEqualKeys = (obj1, obj2) => Object.keys(obj1)
  .every(k => k in obj2 && 
    (typeof obj1[k] != 'object' || typeof obj2[k] == 'object' && toEqualKeys(obj1[k], obj2[k]))
  )
  
console.log(toEqualKeys(object1, object2))
console.log(toEqualKeys(object1, object3))
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