假设你有:
arr = [
{ id:10, name: 'someName1' },
{ id:10, name: 'someName2' },
{ id:11, name: 'someName3' },
{ id:12, name: 'someName4' }
]
因此,要获得独特的物品:
unique = arr
.map(e => e['id'])
.map((e, i, final) => final.indexOf(e) === i && i)
.filter(obj=> arr[obj])
.map(e => arr[e]);
那么,结果将是
unique = [
{ id:10, name: 'someName1' },
{ id:11, name: 'someName3' },
{ id:12, name: 'someName4' }
]
并且,要获得重复的 ID:
duplicateIds = arr
.map(e => e['id'])
.map((e, i, final) => final.indexOf(e) !== i && i)
.filter(obj=> arr[obj])
.map(e => arr[e]["id"])
ID 列表将是
duplicateIds = [10]
因此,要获取重复的对象:
duplicate = arr.filter(obj=> dublicateIds.includes(obj.id));
现在你拥有了:
duplicate = [
{ id:10, name: 'someName1' },
{ id:10, name: 'someName2' }
]
谢谢https://reactgo.com/removeduplicateobjects/