拥有某个相同键值的对象集合进行去重
例如数组:
const data = [
{name: "Kris",
age: "24"
},
{name: "Andy",
age: "25"
},
{
name: "Kitty",
age: "25"
},
{name: "Andy",
age: "25"
},
{
name: "Kitty",
age: "25"
},
{name: "Andy",
age: "25"
},
{name: "Kitty",
age: "25"
}
];
现在我们要去重里面name
重复的对象,这时候我们可以利用reduce
,例子如下
const dataReducer = (prev, cur, idx) => {
let obj = {};
const { name } = cur;
obj[name] = cur;
return {...prev,
...obj
};
};
const reducedData = data.reduce(dataReducer, {});
let newData = Object.values(reducedData);