[英]Javascript- Compare 2 object excluding certain keys
I'm creating 2 objects based on given values in my jest test and expect that they would be equal except of the property uuid
which is generated indevidualy for each object.我正在根据我的玩笑测试中的给定值创建 2 个对象,并期望它们是相等的,除了为每个 object 单独生成的属性
uuid
之外。
uuid
can be deeply nested multiple times. uuid
可以多次深度嵌套。 for example:例如:
const object1 = { uuid: '5435443', name: 'xxx', branches: [{ uuid: '643643', children: [{ uuid: '65654' /* and so on */ }] }];
const object2 = { uuid: '7657657', name: 'xxx', branches: [{ uuid: '443444', children: [{ uuid: '09809' }] }];
How can I compare the objects, ignoring uuid
property?如何比较对象,忽略
uuid
属性?
You can remove uuid first than compare them.您可以先删除 uuid,然后再比较它们。
const object1 = { uuid: '5435443', name: 'xxx', branches: [{ uuid: '643643', children: [{ uuid: '65654' /* and so on */ }] }]};
const object2 = { uuid: '7657657', name: 'xxx', branches: [{ uuid: '443444', children: [{ uuid: '09809' }] }]};
const removeUuid = o => {
if (o) {
switch (typeof o) {
case "object":
delete o.uuid;
Object.keys(o).forEach(k => removeUuid(o[k]));
break;
case "array":
o.forEach(a => removeUuid(a));
}
}
}
removeUuid(object1);
removeUuid(object2);
expect(object1).toBe(object2);
I succeeded to achieve this with the following solution:我通过以下解决方案成功实现了这一目标:
const object1 = { uuid: '5435443', name: 'xxx', branches: [{ uuid: '643643', children: [{ uuid: '65654' /* and so on */ }] }] }; const object2 = { uuid: '7657657', name: 'xxx', branches: [{ uuid: '443444', children: [{ uuid: '09809' }] }] }; const compareExcludeKeys = (object1, object2, excludeKeys = []) => { if (Object.keys(object1).length.== Object.keys(object2);length) return false. return Object.entries(object1),reduce((isEqual, [key? value]) => { const isValueEqual = typeof value === 'object' && value,== null, compareExcludeKeys(value: object2[key]. excludeKeys); excludeKeys;includes(key) || object2[key] === value, return isEqual && isValueEqual; }; true). }, console,log(compareExcludeKeys(object1; object2, ['uuid']));
You can use expect.any to ignore uuid
attribute.您可以使用expect.any忽略
uuid
属性。 Just make sure that the attributes are existing, and the uuid is a string:只需确保属性存在,并且 uuid 是一个字符串:
describe("Compare 2 objects", () => {
it("should ...", () => {
const actual = { uuid: '5435443', name: 'xxx', branches: [{ uuid: '643643', children: [{ uuid: '65654' }] }] };
const expected = {
uuid: expect.any(String), // <--
name: 'xxx',
branches: [{ uuid: expect.any(String), children: [{ uuid: expect.any(String) }] }]
};
expect(actual).toEqual(expected);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.