简体   繁体   English

如何比较两个对象但跳过值而只比较键和键类型?

[英]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.我想使用 Jest 为我的 Node.js 函数编写单元测试,并且需要测试响应 object 是否有一些特定的键。 Something like this:像这样的东西:

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

// Or just a normal function

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

This toEqualKeys function should check equality just for keys not values.这个toEqualKeys function 应该只检查键而不是值的相等性。 And these objects are not instances of a class.这些对象不是 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?是否有任何可用的 NPM 包?

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 :您可以迭代object1中的每个键,检查 object2 中是否存在相同的键,并且 - 如果object1中的关联属性是 object,则来自该 object 的所有键也存在于object2中的类似 ZA8CFDE6331BD59EB66AC96F89111C4 中

 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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM