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

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

当前回答

要从对象数组中删除所有重复项,最简单的方法是使用过滤器:

var uniq={};var arr=[{“id”:“1”},{“id”:“2”};var arrFiltered=arr.filter(obj=>!uniq[obj.id]&&(uniq[obj.id]=true));console.log('arrFiltered',arrFiltered);

其他回答

    function genFilterData(arr, key, key1) {
      let data = [];
      data = [...new Map(arr.map((x) => [x[key] || x[key1], x])).values()];
    
      const makeData = [];
      for (let i = 0; i < data.length; i += 1) {
        makeData.push({ [key]: data[i][key], [key1]: data[i][key1] });
      }
    
      return makeData;
    }
    const arr = [
    {make: "here1", makeText:'hj',k:9,l:99},
    {make: "here", makeText:'hj',k:9,l:9},
    {make: "here", makeText:'hj',k:9,l:9}]

      const finalData= genFilterData(data, 'Make', 'MakeText');
    
        console.log(finalData);

带过滤器的内衬(保留订单)

在数组中查找唯一id。

arr.filter((v,i,a)=>a.findIndex(v2=>(v2.id===v.id))===i)

如果顺序不重要,映射解决方案将更快:使用映射解决方案


多个财产独有(地点和名称)

arr.filter((v,i,a)=>a.findIndex(v2=>['place','name'].every(k=>v2[k] ===v[k]))===i)

所有财产都是唯一的(对于大型阵列来说,这将很慢)

arr.filter((v,i,a)=>a.findIndex(v2=>(JSON.stringify(v2) === JSON.stringify(v)))===i)

通过用findLastIndex替换findIndex来保留最后一次出现。

arr.filter((v,i,a)=>a.findLastIndex(v2=>(v2.place === v.place))===i)

如果您正在使用Lodash库,也可以使用以下函数。它应该删除重复的对象。

var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];
_.uniqWith(objects, _.isEqual);

为我工作

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

这是我的解决方案,将实际数组添加到键值对象中,其中键将是唯一标识,值可以是对象或整个对象的任何属性。

说明:具有重复项的主数组将转换为键/值对象如果Id已存在于唯一对象中,则该值将被覆盖。最后,只需将唯一对象转换为数组。

getUniqueItems(array) {       
        const unique = {};
        // here we are assigning item.name but it could be a complete object.
        array.map(item => unique[item.Id] = item.name);
        // here you can transform your array item like {text: unique[key], value: key} but actually you can do what ever you want
        return Object.keys(unique).map(key => ({text: unique[key], value: key}));
      })
    );
  }