我有一个对象数组:
[
{ id: 1, name: "Bob" },
{ id: 1, name: "Donald" },
{ id: 2, name: "Daryl" }
]
我想去掉具有重复 ID 的对象,留下一个如下所示的数组:
[
{ id: 1, name: "Bob" },
{ id: 2, name: "Daryl" }
]
我不关心剩下哪些对象,只要每个 ID 都是唯一的即可。也许 Underscore 中的任何东西都可以做到这一点?
编辑:这与下面列出的副本不同;我不是要过滤重复的对象,而是要过滤包含相同 ID 的对象。我已经使用 Underscore 完成了这项工作 - 我会很快发布答案。
最佳答案
var out = arr.reduce(function (p, c) {
// if the next object's id is not found in the output array
// push the object into the output array
if (!p.some(function (el) { return el.id === c.id; })) p.push(c);
return p;
}, []);
关于JavaScript 对象数组 : Removing objects with duplicate properties,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32634736/