拥有某个相同键值的对象集合进行去重

例如数组:

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);
 
posted @ 2020-03-19 16:20  蓝海域的春天  阅读(215)  评论(0编辑  收藏  举报