我正在与 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);
IE。对于比较中的任何对象(递归),属性设置为
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
如果有人有更简单或更好的东西,很高兴接受其他答案:-)
关于javascript - 如何在 Lodash 的 isEqualWith 中将缺失和未定义的属性视为等效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57874879/