js数组对象去重的方法,相同的数据并合并在一起

需求:一个数组对象,里面有重复的数据,需要合并在一起

数组对象为

const items = [

  { id: 1, type: "fruit", name: "apple", color: "red" },

  { id: 2, type: "vegetable", name: "carrot", color: "orange" },

  { id: 1, type: "fruit", name: "apple2", size: "medium" },

  { id: 3, type: "fruit", name: "banana", color: "yellow" },

];

从数据可以看出来,id为1的数据有两个,type也相等,把他组合在一起得到

使用reduce累加的方式

const items = [
  { id: 1, type: "fruit", name: "apple", color: "red" },
  { id: 2, type: "vegetable", name: "carrot", color: "orange" },
  { id: 1, type: "fruit", name: "apple2", size: "medium" },
  { id: 3, type: "fruit", name: "banana", color: "yellow" },
];
interface Item {
  id: number;
  type: string;
  name: string;
  color?: string;
  size?: string;
}

function mergeObject(items: Item[]) {
  const result = items.reduce((acc, item) => {
    const key: string = `${item.id}-${item.type}`;
    if (acc[key]) {
      acc[key] = { ...acc[key], ...item };
    } else {
      acc[key] = item;
    }
    return acc;
  }, {});
  console.log(result);
  return Object.values(result);
}
console.log("----------------", mergeObject(items));

结果:

  1. (3) [{…}, {…}, {…}]
    1. 0: {id: 1, type: 'fruit', name: 'apple2', color: 'red', size: 'medium'}
    2. 1: {id: 2, type: 'vegetable', name: 'carrot', color: 'orange'}
    3. 2: {id: 3, type: 'fruit', name: 'banana', color: 'yellow'}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值