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

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 objectsMap = new Map();
const placesName = [
  { place: "here", name: "stuff" },
  { place: "there", name: "morestuff" },
  { place: "there", name: "morestuff" },
];
placesName.forEach((object) => {
  objectsMap.set(object.place, object);
});
console.log(objectsMap);

其他回答

TypeScript解决方案

这将删除重复的对象,并保留对象的类型。

function removeDuplicateObjects(array: any[]) {
  return [...new Set(array.map(s => JSON.stringify(s)))]
    .map(s => JSON.parse(s));
}

这个解决方案最适合我,因为它使用了Array.from方法,而且它的长度更短,可读性更强。

let person = [
{name: "john"}, 
{name: "jane"}, 
{name: "imelda"}, 
{name: "john"},
{name: "jane"}
];

const data = Array.from(new Set(person.map(JSON.stringify))).map(JSON.parse);
console.log(data);

使用ES6“reduce”和“find”数组助手方法的简单解决方案

工作效率高,非常好!

"use strict";

var things = new Object();
things.thing = new Array();
things.thing.push({
    place: "here",
    name: "stuff"
});
things.thing.push({
    place: "there",
    name: "morestuff"
});
things.thing.push({
    place: "there",
    name: "morestuff"
});

// the logic is here

function removeDup(something) {
    return something.thing.reduce(function (prev, ele) {
        var found = prev.find(function (fele) {
            return ele.place === fele.place && ele.name === fele.name;
        });
        if (!found) {
            prev.push(ele);
        }
        return prev;
    }, []);
}
console.log(removeDup(things));

我认为最好的方法是使用reduce和Map对象。这是单线解决方案。

常量数据=[{id:1,名称:“David”},{id:2,名称:“Mark”},{id:2,名称:“Lora”},{id:4,名称:“Tyler”},{id:4,名称:“Donald”},{id:5,名称:“Adrian”},{id:6,姓名:“Michael”}]constuniqueData=[…data.reduce((map,obj)=>map.set(obj.id,obj),new map()).values()];console.log(uniqueData)/*在`map.set(obj.id,obj)中`“obj.id”是键。(别担心。我们将只使用.values()方法获取值)“obj”是整个对象。*/

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

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

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);