Javascript 两个对象数组之间相减

Javascript Subtract between two arrays of objects

您好,谁能帮我实现 right/clean 两个对象数组之间的减法方法。我的情况(后端)是我从 mongodb 获取产品数据,然后我还有从 MySql 获取的手推车数据,我想做的是如果产品库存减去数量在手推车中,结果低于 0,那么我将抛出错误。正确知道我的实现如下:

 const trolleyProducts = await Trolley.findAll({
    where: {
      userId,
      isActive: true,
    },
    attributes: ["id", "productId", "quantity", "notes"],
  });
 
 const products = await ProductModel.find(
    {
      dbId: trolleyProductIds,
    },
    {
      _id: 0,
      sku: 0,
      barcode: 0,
      reservedStock: 0,
      sold: 0,
      tags: 0,
      infos: 0,
      photosURL: 0,
    }
  );
  
  // ******* here is my implementation *******
  products.map((product) => {
    trolleyProducts.map((trolley) => {
      if (product.dbId === trolley.productId) {
        if (product.stock - trolley.quantity < 0) {
          throw {
            name: "Bad Request",
            message: " Stock is less than desired quantity",
          };
        }
      }
    });
  });
  // **************

请让我知道是否有比我的更好更清洁的方法(性能问题)。谢谢:)

您可以将 trolleyProducts 转换为以产品 ID 为键的对象。这样您就不需要嵌套循环来查找匹配的产品。

此外,当回调函数 returns 一个值并且您正在制作这些值的数组时,应使用 map()。如果循环仅用于副作用,请使用 forEach()

const trolleyProducts = await Trolley.findAll({
  where: {
    userId,
    isActive: true,
  },
  attributes: ["id", "productId", "quantity", "notes"],
});
// convert array to object.
trolleyProducts = Object.fromEntries(trolleyProducts.map(obj => [obj.productId, obj]));

const products = await ProductModel.find({
  dbId: trolleyProductIds,
}, {
  _id: 0,
  sku: 0,
  barcode: 0,
  reservedStock: 0,
  sold: 0,
  tags: 0,
  infos: 0,
  photosURL: 0,
});

products.forEach((product) => {
  const trolley = trolleyProducts[product.dbId]
  if (trolley && product.stock - trolley.quantity < 0) {
    throw {
      name: "Bad Request",
      message: `Stock is less than desired quantity for ${product.dbId}`,
    };
  }
});