javascript - 查找仅包含不同对象的数组

标签 javascript arrays

我有一个数组:

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 中执行此操作。

最佳答案

您可以通过在 Set 中查找 id 来过滤数组。

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);

关于javascript - 查找仅包含不同对象的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56933597/

相关文章:

javascript - 在表格中的特定行周围添加边框

ios - 将字符串转换为 Int 数组

c - 使用 getchar() 和 putchar() 用数组输入和输出一组字符

JAVA类数组

javascript - 如何将查询结果推送到node.js中的数组变量?

javascript - FullCalendar - 是否可以更改/添加文本?

javascript - 合并两个 JavaScript 对象

javascript - 显示隐藏的跨度元素Javascript

javascript - jQuery 验证未按预期工作

arrays - Swift 3 比较数组索引