首页 > 解决方案 > 从对象数组中删除重复项并在 JavaScript 中添加新值(例如数量)

问题描述

我有一个包含对象数组的对象。我想删除重复的对象,我想给它附加新的值,比如数量。

const data = [{
      id: "B01",
      image: "https://i.ibb.co/zmdvMfD/zinger-stacke-burger.png",
      title: "Zinger Stack",
      price: 3.99,
    },
    {
      id: "B01",
      image: "https://i.ibb.co/zmdvMfD/zinger-stacke-burger.png",
      title: "Zinger Stack",
      price: 3.99,
    },
    {
      id: "F01",
      image: "https://i.ibb.co/zmdvMfD/zinger-stacke-burger.png",
      title: "Zinger Stack",
      price: 3.99,
    },
    {
      id: "F01",
      image: "https://i.ibb.co/zmdvMfD/zinger-stacke-burger.png",
      title: "Zinger Stack",
      price: 3.99,
    },
    ]

这就是我想要实现的

const data = [
    {
      id: "B01",
      image: "https://i.ibb.co/zmdvMfD/zinger-stacke-burger.png",
      title: "Zinger Stack",
      price: 3.99,
      quantity: 2
    },
    {
      id: "F01",
      image: "https://i.ibb.co/zmdvMfD/zinger-stacke-burger.png",
      title: "Zinger Stack",
      price: 3.99,
      quantity: 2
    }
    ]

这是我的解决方案。是否有任何速记/更快的方法来达到相同的结果?

  let ids = data.map((o) => o.id);
  let uniqueList = data.filter(({ id }, index) => !ids.includes(id, index + 1));

  console.log("uniqueList", uniqueList);


 const result = uniqueList.map((item) => {
    return {
      ...item,
      quantity: (data.reduce((totalType, item) => {
        if (!totalType[item.id]) {
          totalType[item.id] = 0;
        }
    
        totalType[item.id]++;
    
        return totalType;
      }, {}))[item.id]
    };
  });

  console.log("result >", result);

标签: javascripthigher-order-functions

解决方案


您可以通过简单的迭代来实现这一点:

const map = new Map();

data.forEach((item) => {
   if (map.has(item.id)) {
      map.get(item.id).quantity++;
   }
   else {
      map.set(item.id, {
         ...item,
         quantity: 1
      })
   }
});

const result = Array.from(map.values());

推荐阅读