Javascript 基于两个属性的数组中的唯一对象
假设我们有一个对象数组:Javascript 基于两个属性的数组中的唯一对象,javascript,object,unique-values,Javascript,Object,Unique Values,假设我们有一个对象数组: results = [ {id: 1, name: John}, {id: 2, name: Gabo}, {id: 1, name: Anna}, {id: 3, name: Gabo} {id: 1, name: Jack}, ] 我想要一个函数,它可以获取所有这些对象,这些对象具有唯一的id和名称,并且它的值不在其他对象中 results = [ {id: 1, name: John}, // unique id-name so we add to arr
results = [
{id: 1, name: John},
{id: 2, name: Gabo},
{id: 1, name: Anna},
{id: 3, name: Gabo}
{id: 1, name: Jack}, ]
我想要一个函数,它可以获取所有这些对象,这些对象具有唯一的id和名称,并且它的值不在其他对象中
results = [
{id: 1, name: John}, // unique id-name so we add to array
{id: 2, name: Gabo}, // unique id-name so we add to array
{id: 1, name: Anna}, // name is unique but object with this id already exists in array so we reject
{id: 3, name: Gabo} // id is unique but object with this name already exists in array so we reject
{id: 1, name: Jack}, ] //etc..
您可以使用Set注册,然后快速检查重复的id或名称:
什么不起作用?我在寻找最短的解决方案我想要的不是问题而是请求。StackOverflow不是这样工作的。请阅读。我投票结束这个问题,因为它基本上只是要求请为我写代码。
results = [
{id: 1, name: John},
{id: 2, name: Gabo},
function getUniq(items) {
const ids = new Set();
const names = new Set();
return items.filter((item) => {
if (ids.has(item.id) || names.has(item.name)) {
return false;
}
ids.add(item.id);
names.add(item.name);
return true;
});
}