我正在尝试重构一些代码以使用 javascript 过滤器函数来删除具有相同属性的对象。
schemas = schemas.filter((schema, index, newArray) => {
return index === schemas.findIndex(obj => obj.className == schema.className)
})
schemas 是一个自定义对象 NameSchema 的数组:
interface NameSchema {
schemaId: string;
className: string;
}
我在使用 findIndex 方法时遇到两个问题,编译器提示 NameSchema 上不存在 findIndex,并且数组中的许多对象具有相同的属性,但不是相同的对象。
如何使用 Array.filter 函数获取不具有相同类名的对象的对象列表?
编辑
我在这里找到了答案:Remove duplicates from an array of objects in JavaScript
我的代码最终看起来像这样:
schemas = schemas.filter((schema, index, self) => index === self.findIndex((obj) => (obj.className === schema.className)))
最佳答案
这有帮助吗?
const array = [
{id: 1, val: 'hello 1a'},
{id: 1, val: 'hello 1b'},
{id: 2, val: 'hello 2a'},
{id: 2, val: 'hello 2b'},
]
const filteredArray = array.filter((obj, index, arr) => {
return arr.map(mapObj => mapObj.id).indexOf(obj.id) === index;
});
console.log(filteredArray)
关于javascript - 使用 javascript .filter() 删除重复的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55365223/