Tim*_*rry 8 javascript equality lodash
我正在与 Lodash 的自定义比较函数进行斗争_.isEqualWith
。我想要一个这样的函数:
const comparisonFunc = /* ...TBC... */
// Should be true:
_.isEqualWith({ a: undefined }, { }, comparisonFunc);
// Should still be false, as normal:
_.isEqualWith({ a: undefined }, { a: 123 }, comparisonFunc);
// Should still be false, as normal:
_.isEqualWith([undefined], [ ], comparisonFunc);
Run Code Online (Sandbox Code Playgroud)
即,对于比较中的任何对象(递归地),设置为 的属性undefined
应被视为不存在。
这并不像我想要的那么简单,但我找到了解决方案:
const comparisonFunc = (a, b) => {
if (_.isArray(a) || _.isArray(b)) return;
if (!_.isObject(a) || !_.isObject(b)) return;
if (!_.includes(a, undefined) && !_.includes(b, undefined)) return;
// Call recursively, after filtering all undefined properties
return _.isEqualWith(
_.omitBy(a, (value) => value === undefined),
_.omitBy(b, (value) => value === undefined),
comparisonFunc
);
}
// Should be true:
_.isEqualWith({ a: undefined }, { }, comparisonFunc); // = true
// Should still be false, as normal:
_.isEqualWith({ a: undefined }, { a: 123 }, comparisonFunc); // = false
// Should still be false, as normal:
_.isEqualWith([undefined], [ ], comparisonFunc); // = false
Run Code Online (Sandbox Code Playgroud)
如果有人有更简单或更好的东西,很乐意接受其他答案:-)
归档时间: |
|
查看次数: |
3611 次 |
最近记录: |