我有一个包含对象数组的对象。
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);
使用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));