我有一个数组:
var objArray = [
{ id: 0, name: ‘Object 0’, otherProp: ‘321’ },
{ id: 1, name: ‘O1’, otherProp: ‘648’ },
{ id: 2, name: ‘Another Object’, otherProp: ‘850’ },
{ id: 3, name: ‘Almost There’, otherProp: ‘046’ },
{ id: 4, name: ‘Last Obj’, otherProp: ‘984’ },
{ id: 0, name: ‘Object 0’, otherProp: ‘321’ }
];
此处的id 0加两次。我只想要一个没有相同对象的数组。
预期输出:
a = [
{ id: 0, name: ‘Object 0’, otherProp: ‘321’ },
{ id: 1, name: ‘O1’, otherProp: ‘648’ },
{ id: 2, name: ‘Another Object’, otherProp: ‘850’ },
{ id: 3, name: ‘Almost There’, otherProp: ‘046’ },
{ id: 4, name: ‘Last Obj’, otherProp: ‘984’ }]
如何使用JavaScript做到这一点。
答案 0 :(得分:3)
您可以通过在id
中查找Set
来过滤数组。
var array = [{ id: 0, name: 'Object 0', otherProp: '321' }, { id: 1, name: 'O1', otherProp: '648' }, { id: 2, name: 'Another Object', otherProp: '850' }, { id: 3, name: 'Almost There', otherProp: '046' }, { id: 4, name: 'Last Obj', otherProp: '984' }, { id: 0, name: 'Object 0', otherProp: '321' }],
seen = new Set,
result = array.filter(({ id }) => !seen.has(id) && seen.add(id));
console.log(result);