我有一个包含对象数组的对象。
obj = {};
obj.arr = new Array();
obj.arr.push({place:"here",name:"stuff"});
obj.arr.push({place:"there",name:"morestuff"});
obj.arr.push({place:"there",name:"morestuff"});
我想知道从数组中删除重复对象的最佳方法是什么。例如,obj.arr将变成。。。
{place:"here",name:"stuff"},
{place:"there",name:"morestuff"}
这是如何从对象数组中删除重复性的简单方法。
我经常处理数据,这对我很有用。
const data = [{name: 'AAA'}, {name: 'AAA'}, {name: 'BBB'}, {name: 'AAA'}];
function removeDuplicity(datas){
return datas.filter((item, index,arr)=>{
const c = arr.map(item=> item.name);
return index === c.indexOf(item.name)
})
}
console.log(removeDuplicity(data))
将打印到控制台:
[[object Object] {
name: "AAA"
}, [object Object] {
name: "BBB"
}]
这种方式对我很有效:
function arrayUnique(arr, uniqueKey) {
const flagList = new Set()
return arr.filter(function(item) {
if (!flagList.has(item[uniqueKey])) {
flagList.add(item[uniqueKey])
return true
}
})
}
const data = [
{
name: 'Kyle',
occupation: 'Fashion Designer'
},
{
name: 'Kyle',
occupation: 'Fashion Designer'
},
{
name: 'Emily',
occupation: 'Web Designer'
},
{
name: 'Melissa',
occupation: 'Fashion Designer'
},
{
name: 'Tom',
occupation: 'Web Developer'
},
{
name: 'Tom',
occupation: 'Web Developer'
}
]
console.table(arrayUnique(data, 'name'))// work well
打印输出
┌─────────┬───────────┬────────────────────┐
│ (index) │ name │ occupation │
├─────────┼───────────┼────────────────────┤
│ 0 │ 'Kyle' │ 'Fashion Designer' │
│ 1 │ 'Emily' │ 'Web Designer' │
│ 2 │ 'Melissa' │ 'Fashion Designer' │
│ 3 │ 'Tom' │ 'Web Developer' │
└─────────┴───────────┴────────────────────┘
ES5:
function arrayUnique(arr, uniqueKey) {
const flagList = []
return arr.filter(function(item) {
if (flagList.indexOf(item[uniqueKey]) === -1) {
flagList.push(item[uniqueKey])
return true
}
})
}
这两种方式更简单易懂。
我知道这个问题已经有很多答案了,但请耐心等待。。。
数组中的某些对象可能具有您不感兴趣的其他财产,或者您只想查找只考虑财产子集的唯一对象。
考虑下面的数组。假设您想仅考虑propOne和propTwo来查找此数组中的唯一对象,而忽略可能存在的任何其他财产。
预期结果应仅包括第一个和最后一个对象。代码如下:
常量数组=[{propOne:“a”,propTwo:“b”,第三题:“我没有参与……”},{propOne:“a”,propTwo:“b”,someOtherProperty:“没有人关心这个…”},{propOne:'x',propTwo:'y',yetAotherJunk:“我真的一文不值”,这个:“我有一些别人没有的东西”}];常量uniques=[…新集合(array.map(x=>JSON.stringify(((o)=>({propOne:o.propOne,propTwo:o.propTwo}))(x) ))].map(JSON.parse);console.log(uniques);