我有一个包含对象数组的对象。
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"}
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);
这里是ES6的解决方案,您只想保留最后一项。该解决方案功能强大,符合Airbnb风格。
const things = {
thing: [
{ place: 'here', name: 'stuff' },
{ place: 'there', name: 'morestuff1' },
{ place: 'there', name: 'morestuff2' },
],
};
const removeDuplicates = (array, key) => {
return array.reduce((arr, item) => {
const removed = arr.filter(i => i[key] !== item[key]);
return [...removed, item];
}, []);
};
console.log(removeDuplicates(things.thing, 'place'));
// > [{ place: 'here', name: 'stuff' }, { place: 'there', name: 'morestuff2' }]