问题描述
寻找有关为什么以下代码无法正确过滤的解释。我有一个对象数组,其中一个属性是buy_mth_yr,其格式为mmm-yy,如下所示。
buy_mth_yr : 'Apr-18'
我正在尝试获取所有唯一的 buy_mth_yr 值的列表,并作为标签值对象的列表返回,以传递到过滤器中。我已经在一个单独的堆栈溢出问题中找到了一个解决方案,我提出这个问题的目的更多是为了理解为什么我下面的原始解决方案不起作用。所以让我们说 data
是我的带有 buy_mth_yr 键的对象列表。 if 语句每次都调用,我最终得到一个未过滤的列表。任何帮助/见解表示赞赏!
let distinct = [];
data.forEach(record =>{
let temp = {label: record.buy_mth_yr,value: record.buy_mth_yr}
if(!(temp in distinct)){
distinct.push(temp)
}
})
return distinct;
解决方法
了解为什么我下面的原始解决方案不起作用
因为您正在进行参考比较 - 谷歌上弹出的第一个链接,它可能有帮助:https://dmitripavlutin.com/how-to-compare-objects-in-javascript/#1-referential-equality
({a:1}) !== ({a:1})
// but
const obj = {a:1};
obj === obj
temp
将永远出现在 distinct
中,因为它每次都是一个新对象。
编辑:
除此之外,一个更好的解决方案(有上千种方法可以编写,下面只是一个示例)如下所示:
const isShallowEqualWith = (a) => (b) => {
const keysA = Object.keys(a);
const keysB = Object.keys(b);
return keysA.length === keysB.length && keysA.every(k => a[k] === b[k]);
}
let distinct = [];
data.forEach(record =>{
let temp = {label: record.buy_mth_yr,value: record.buy_mth_yr}
if(!distinct.find(isShallowEqualWith(temp)) {
distinct.push(temp);
}
})
return distinct;
,
我认为您的 !(temp in distinct)
不是您想做的检查:改用 !distinct.includes(temp)
。
但是,您应该查看具有 _.uniq
和 _.uniqBy
函数的 lodash 库:https://www.loom.com/share/3a891109ef3449608a1aeae11ebc21ef