我正在尝试使用 lodash 进行忽略未定义值的相等比较。
我希望以下内容起作用:
console.log(
isEqualWith(request.body, actualRequest.body.json, (a, b) => {
console.log(a, b, a === undefined && b === undefined ? true : undefined
);
return a === undefined && b === undefined ? true : undefined;
})
);
Run Code Online (Sandbox Code Playgroud)
但是,控制台输出在(整个对象的)“第一次”比较时失败,即使定制程序返回未定义。这是输出:
{ item1: undefined, item2: 'test'} { item2: 'test' } undefined
false
Run Code Online (Sandbox Code Playgroud)
除了第一个对象,它从不比较任何东西。我希望输出如下:
{ item1: undefined, item2: 'test'} { item2: 'test' } undefined
undefined undefined true
'test' 'test' undefined
true
Run Code Online (Sandbox Code Playgroud)
因为,假设自定义程序在第一次检查时返回 undefined,那么它会遍历对象的字段并对这些字段执行自定义程序检查。
在返回undefined对象的情况下,该方法_.isEqualWith()会进行多次比较以决定对象是否相等。它实际上检查两个对象中的键数是否相同,这在您的情况下失败。如果它具有相同数量的密钥,则在进行 hasOwnProperty 检查时会失败。
要进行忽略undefined值的部分比较,请使用_.isMatch(),它实际上使用相同的逻辑,但length通过设置bitmaskfor忽略(和其他检查)COMPARE_PARTIAL_FLAG。
const o1 = { item1: undefined, item2: 'test' }
const o2 = { item2: 'test' }
const result = _.isMatch(o1, o2)
console.log(result)Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2703 次 |
| 最近记录: |