我有一个包含对象数组的对象。

obj = {};

obj.arr = new Array();

obj.arr.push({place:"here",name:"stuff"});
obj.arr.push({place:"there",name:"morestuff"});
obj.arr.push({place:"there",name:"morestuff"});

我想知道从数组中删除重复对象的最佳方法是什么。例如,obj.arr将变成。。。

{place:"here",name:"stuff"},
{place:"there",name:"morestuff"}

当前回答

如果您发现需要经常基于特定字段从数组中删除重复的对象,那么创建一个可以从项目中任何位置导入的独特(数组、谓词)函数可能是值得的。这看起来像

const things = [{place:"here",name:"stuff"}, ...];
const distinctThings = distinct(things, thing => thing.place);

不同的函数可以使用上面许多好答案中给出的任何实现。最简单的方法是使用findIndex:

const distinct = (items, predicate) => items.filter((uniqueItem, index) =>
    items.findIndex(item =>
        predicate(item) === predicate(uniqueItem)) === index);

其他回答

const uniqueElements = (arr, fn) => arr.reduce((acc, v) => {
    if (!acc.some(x => fn(v, x))) { acc.push(v); }
    return acc;
}, []);

const stuff = [
    {place:"here",name:"stuff"},
    {place:"there",name:"morestuff"},
    {place:"there",name:"morestuff"},
];

const unique = uniqueElements(stuff, (a,b) => a.place === b.place && a.name === b.name );
//console.log( unique );

[{
    "place": "here",
    "name": "stuff"
  },
  {
    "place": "there",
    "name": "morestuff"
}]

如果您希望基于所有参数而不仅仅是一个参数来消除数组的重复。可以使用lodash的uniqBy函数,该函数可以将函数作为第二个参数。

您将拥有这一行:

 _.uniqBy(array, e => { return e.place && e.name })

您可以将数组对象转换为字符串,以便对其进行比较,将字符串添加到集合中,以便自动删除可比较的重复项,然后将每个字符串转换回对象。

它可能不像其他答案那样有表现力,但它是可读的。

const things = {};

things.thing = [];
things.thing.push({place:"here",name:"stuff"});
things.thing.push({place:"there",name:"morestuff"});
things.thing.push({place:"there",name:"morestuff"});

const uniqueArray = (arr) => {

  const stringifiedArray = arr.map((item) => JSON.stringify(item));
  const set = new Set(stringifiedArray);

  return Array.from(set).map((item) => JSON.parse(item));
}

const uniqueThings = uniqueArray(things.thing);

console.log(uniqueThings);

您还可以创建一个通用函数,该函数将根据传递给该函数的对象键过滤数组

function getUnique(arr, comp) {

  return arr
   .map(e => e[comp])
   .map((e, i, final) => final.indexOf(e) === i && i)  // store the keys of the unique objects
   .filter(e => arr[e]).map(e => arr[e]); // eliminate the dead keys & store unique objects

 }

你可以这样调用函数,

getUnique(things.thing,'name') // to filter on basis of name

getUnique(things.thing,'place') // to filter on basis of place

这个问题可以简化为从对象数组中删除重复项。

您可以通过使用一个对象来维护作为键的唯一条件并存储相关值来实现更快的O(n)解决方案(假设本机键查找可以忽略不计)。

基本上,这个想法是用唯一的键存储所有对象,这样重复的对象就会覆盖自己:

const thing=[{地点:“这里”,名称:“stuff”},{地点“那里”,名称“morestuff”},{地方:“那里”、名称:“morestuff]常量uniques={}用于(事物的常量){const key=t.place+'$'+t.name//或您想要的任何字符串条件,可以将其生成为Object.keys(t).join(“$”)uniques[key]=t//上次重复获胜}constuniqueThing=对象.values(uniques)console.log(uniqueThing)