简体   繁体   English

从对象数组中删除重复项并在 JavaScript 中添加新值(例如数量)

[英]Remove duplicates from an array of objects and Add new Value (e.g. Quantity) in JavaScript

I have an object that contains an array of objects.我有一个包含对象数组的 object。 I want to remove the duplicated object and i want to append it with new value such as quantity.我想删除重复的 object 并且我想用新的值(例如数量)来 append 它。

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,
    },
    ]

This is what i want to achieve这就是我想要实现的

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
    }
    ]

This one is my solution.这是我的解决方案。 is there any shorthand/ faster way to achieve the same result?是否有任何速记/更快的方法来达到相同的结果?

  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);

You can achieve this with a simple iteration:您可以通过简单的迭代来实现这一点:

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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM