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

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"}

当前回答

你听说过洛达什图书馆吗?当您不想将逻辑应用于代码时,我建议您使用此实用程序,并使用已优化且可靠的现有代码。

考虑制作一个这样的数组

things.thing.push({place:"utopia",name:"unicorn"});
things.thing.push({place:"jade_palace",name:"po"});
things.thing.push({place:"jade_palace",name:"tigress"});
things.thing.push({place:"utopia",name:"flying_reindeer"});
things.thing.push({place:"panda_village",name:"po"});

注意,如果您想保持一个属性的唯一性,您可以使用lodash库来实现这一点。在这里,您可以使用_.uniqBy

.uniqBy(数组,[iteratee=.identity])

此方法类似于_.uniq(它返回一个数组的无重复版本,其中只保留每个元素的第一次出现),只是它接受iterate,iterate为数组中的每个元素调用,以生成计算唯一性的标准。

因此,例如,如果要返回具有唯一属性“place”的数组

_.uniqBy(things.thing,'place')

同样,如果您希望唯一属性为“name”

_.uniqBy(things.thing,'name')

希望这有帮助。

干杯

其他回答

来源

JSFiddle公司

这将在不传递任何键的情况下删除重复对象。

uniqueArray=a=>[…new Set(.map(o=>JSON.stringify(o))].map(s=>JSON.parse(s));var objects=[{'x':1,'y':2},{'x':2,'y':1},{'x':1,'y':2}];var unique=uniqueArray(对象);console.log(“原始对象”,对象);console.log(“唯一”,唯一);

uniqueArray = a => [...new Set(a.map(o => JSON.stringify(o)))].map(s => JSON.parse(s));

    var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];

    var unique = uniqueArray(objects);
    console.log(objects);
    console.log(unique);

常量=[{地点:“这里”,名称:“东西”},{地点:“there”,名称:“morestuff”},{地点:“there”,名称:“morestuff”}];constfilteredArr=things.reduce((thing,current)=>{const x=thing.find(item=>item.place==current.place);如果(!x){return thing.concat([current]);}其他{归还物品;}}, []);console.log(filteredArr)

通过设置对象解决方案|根据数据类型

const seed=new Set();常量=[{地点:“这里”,名称:“东西”},{地点:“there”,名称:“morestuff”},{地点:“there”,名称:“morestuff”}];constfilteredArr=things.filter(el=>{const duplicate=已看到。有(el.place);见添加(el.place);回来复制});console.log(filteredArr)

设置对象特征

Set Object中的每个值都必须是唯一的,将检查值是否相等

根据数据类型(无论是原始值还是对象引用)设置对象存储唯一值的目的。它有四个非常有用的实例方法add、clear、has和delete。

唯一的数据类型功能(&D):。。

加法

默认情况下,它将唯一数据推送到集合中,并保留数据类型。。这意味着它可以防止将重复项推入集合,并且默认情况下还会检查数据类型。。。

has方法

有时需要检查数据项是否存在于集合和中。这是集合检查唯一id或项和数据类型的简便方法。。

删除方法

它将通过标识数据类型从集合中删除特定项。。

清除方法

它将从一个特定变量中删除所有集合项,并将其设置为空对象

Set对象还具有迭代方法和更多功能。。

更好地从这里阅读:Set-JavaScript | MDN

来点es6魔法怎么样?

obj.arr = obj.arr.filter((value, index, self) =>
  index === self.findIndex((t) => (
    t.place === value.place && t.name === value.name
  ))
)

参考URL

更通用的解决方案是:

const uniqueArray = obj.arr.filter((value, index) => {
  const _value = JSON.stringify(value);
  return index === obj.arr.findIndex(obj => {
    return JSON.stringify(obj) === _value;
  });
});

使用上述属性策略而不是JSON.stringify:

const isPropValuesEqual = (subject, target, propNames) =>
  propNames.every(propName => subject[propName] === target[propName]);

const getUniqueItemsByProperties = (items, propNames) => 
  items.filter((item, index, array) =>
    index === array.findIndex(foundItem => isPropValuesEqual(foundItem, item, propNames))
  );

如果希望propNames属性为数组或值,可以添加包装器:

const getUniqueItemsByProperties = (items, propNames) => {
  const propNamesArray = Array.from(propNames);

  return items.filter((item, index, array) =>
    index === array.findIndex(foundItem => isPropValuesEqual(foundItem, item, propNamesArray))
  );
};

允许getUniqueItemsByProperty('a')和getUniqueItemsByProperty(['a']);

Stackblitz示例

解释

首先了解使用的两种方法:过滤器,findIndex接下来,让你的想法让你的两个对象相等,并记住这一点。如果某个东西满足我们刚刚想到的标准,我们可以将其检测为复制品,但它的位置不在具有该标准的对象的第一个实例处。因此,我们可以使用上述标准来确定某个东西是否是重复的。

任何对象数组的泛型:

/**
* Remove duplicated values without losing information
*/
const removeValues = (items, key) => {
  let tmp = {};

  items.forEach(item => {
    tmp[item[key]] = (!tmp[item[key]]) ? item : Object.assign(tmp[item[key]], item);
  });
  items = [];
  Object.keys(tmp).forEach(key => items.push(tmp[key]));

  return items;
}

希望这对任何人都有帮助。

向列表中再添加一个。将ES6和Array.reduce与Array.find一起使用。在此示例中,根据guid属性筛选对象。

let filtered = array.reduce((accumulator, current) => {
  if (! accumulator.find(({guid}) => guid === current.guid)) {
    accumulator.push(current);
  }
  return accumulator;
}, []);

扩展此选项以允许选择属性并将其压缩为一行:

const uniqify = (array, key) => array.reduce((prev, curr) => prev.find(a => a[key] === curr[key]) ? prev : prev.push(curr) && prev, []);

要使用它,请将对象数组和要进行重复数据消除的键的名称作为字符串值传递:

const result = uniqify(myArrayOfObjects, 'guid')