使用foreach()在后端找到猫中物品的价格

发布于 2025-02-09 20:43:51 字数 1154 浏览 2 评论 0原文

我正在尝试将付款网关系统实现到我正在从事的项目中,我需要将购物车总计在后端而不是在前端。我正在尝试使用foreach()redain()来完成此操作。我正在努力的部分是通过我所有产品的_id s进行过滤,然后找到与购物车中与我的物品关联的_idscartinfo ),然后从那里获取_ids与购物车中项目的_ids匹配的项目的价格。下面,我包括到目前为止的内容。我非常感谢有关如何执行此操作的任何帮助或指导。谢谢你!

const total = products.forEach(x => {
    if (x._id === cartInfo._id) {
      const itemsTotal = x.price * cartInfo.qty
      }
    })
  
const sum = itemsTotal.reduce((a, b) => a + b, 0)

产品是所有产品的数组,cartinfo包含_id s and QTY s购物车中的产品。

Cartinfo的示例:

0: {_id: '624bc7fe0f91078261ab6529', qty: 1}
1: {_id: '624bc8240f91078261ab6531', qty: 2}

产品示例:

0: {_id: '624bc7fe0f91078261ab6529', name: sample 1, price: 30, countInStock: 10}
1: {_id: '624bc8240f91078261ab6531', name: sample 2, price 10, countInStock: 4}
2: {_id: '624bc1a50f91078261ab650d', name: sample 3, price 15, countInStock: 1}
3: {_id: '62562017645f1882e45adc32', name: sample 4, price 20, countInStock: 7}

I'm trying to implement a payment gateway system into a project that I'm working on, and I need to get the cart total in the backend instead of just in the frontend. I'm trying to do this with forEach() and reduce(). The part that I am struggling with is filtering through _ids from all of my products to then find the _ids associated with my items in my cart (cartInfo), and then from there getting the price of the items whose _ids match the _ids of the items in the cart. Below, I have included what I have so far. I would really appreciate any help or guidance on how to do this. Thank you!

const total = products.forEach(x => {
    if (x._id === cartInfo._id) {
      const itemsTotal = x.price * cartInfo.qty
      }
    })
  
const sum = itemsTotal.reduce((a, b) => a + b, 0)

products is an array of all of the products and cartInfo contains the _ids and qtys of each of the products in the cart.

Example of cartInfo:

0: {_id: '624bc7fe0f91078261ab6529', qty: 1}
1: {_id: '624bc8240f91078261ab6531', qty: 2}

Example of products:

0: {_id: '624bc7fe0f91078261ab6529', name: sample 1, price: 30, countInStock: 10}
1: {_id: '624bc8240f91078261ab6531', name: sample 2, price 10, countInStock: 4}
2: {_id: '624bc1a50f91078261ab650d', name: sample 3, price 15, countInStock: 1}
3: {_id: '62562017645f1882e45adc32', name: sample 4, price 20, countInStock: 7}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

甜味拾荒者 2025-02-16 20:43:51

为了获得可读性和循环优化,我更喜欢为... 语句的简单用于此类方案:

let cartInfo = [
  {
    _id: `624bc7fe0f91078261ab6529`,
    qty: 1
  },
  {
    _id: `624bc8240f91078261ab6531`,
    qty: 2
  },
];

let products = [
  {
    _id: `624bc7fe0f91078261ab6529`,
    name: `sample 1`,
    price: 30,
    countInStock: 10
  },
  {
    _id: `624bc8240f91078261ab6531`,
    name: `sample 2`,
    price: 10,
    countInStock: 4
  },
  {
    _id: `624bc1a50f91078261ab650d`,
    name: `sample 3`,
    price: 15,
    countInStock: 1
  },
  {
    _id: `62562017645f1882e45adc32`,
    name: `sample 4`,
    price: 20,
    countInStock: 7
  },
];

let cartTotalPrice = 0;

for (cartItem of cartInfo) {
  for (product of products) {
    if (cartItem._id === product._id) {
      cartTotalPrice += (product.price * cartItem.qty);
      break;
    };
  };
};

console.log(cartTotalPrice);

该解决方案的可读性方面是主观的,但是我认为此代码看起来更加人性化 -比方法和回调功能友好。

此处使用的语句的还将提供使用break语句分解给定循环的能力。因此,在此上下文中,如果购物车中的一个项目与循环的嵌套迭代中的产品数组中的项目匹配,则不会针对该项目产品阵列在随后的循环中再次。有了这个特定的数据集和解决方案,这将使整体循环从8到3下降到3。您可能可以想象,随着较大的购物车尺寸和产品目录,性能优势将非常重要。

希望这会有所帮助。

For readability and loop optimisation, I prefer the simple for...of statement for these kinds of scenarios:

let cartInfo = [
  {
    _id: `624bc7fe0f91078261ab6529`,
    qty: 1
  },
  {
    _id: `624bc8240f91078261ab6531`,
    qty: 2
  },
];

let products = [
  {
    _id: `624bc7fe0f91078261ab6529`,
    name: `sample 1`,
    price: 30,
    countInStock: 10
  },
  {
    _id: `624bc8240f91078261ab6531`,
    name: `sample 2`,
    price: 10,
    countInStock: 4
  },
  {
    _id: `624bc1a50f91078261ab650d`,
    name: `sample 3`,
    price: 15,
    countInStock: 1
  },
  {
    _id: `62562017645f1882e45adc32`,
    name: `sample 4`,
    price: 20,
    countInStock: 7
  },
];

let cartTotalPrice = 0;

for (cartItem of cartInfo) {
  for (product of products) {
    if (cartItem._id === product._id) {
      cartTotalPrice += (product.price * cartItem.qty);
      break;
    };
  };
};

console.log(cartTotalPrice);

The readability aspect of this solution is subjective, but I just think this code looks a lot more human-friendly than methods and callback functions.

The for...of statements used here will also provide the ability to break-out of a given loop with the break statement. So in this context, if an item in the cart is matched to an item in products array in an iteration of the nested for...of loop, that same cart item won't be queried against the products array again in subsequent loops. With this specific dataset and solution, this brings the overall loops down from 8 to 3. You can probably imagine that with larger cart sizes and product catalogues, the performance benefits would be pretty significant.

Hope this helps.

你是我的挚爱i 2025-02-16 20:43:51

因此,专门使用要使用的方法。您可以做类似的事情。我更改的主要内容是首先迭代购物车,然后使用查找方法将购物车ID与产品ID匹配。

const cart = [{
    _id: '624bc7fe0f91078261ab6529',
    qty: 1
  },
  {
    _id: '624bc8240f91078261ab6531',
    qty: 2
  }
]

const products = [{
    _id: '624bc7fe0f91078261ab6529',
    name: 'sample 1',
    price: 30,
    countInStock: 10
  },
  {
    _id: '624bc8240f91078261ab6531',
    name: 'sample 2',
    price: 10,
    countInStock: 4
  },
  {
    _id: '624bc1a50f91078261ab650d',
    name: 'sample 3',
    price: 15,
    countInStock: 1
  },
  {
    _id: '62562017645f1882e45adc32',
    name: 'sample 4',
    price: 20,
    countInStock: 7
  }
]

const cartTotals = [];
cart.forEach((product) => {
  const matchedProduct = products.find(element => element._id === product._id);
  if (matchedProduct) {
    cartTotals.push(product.qty * matchedProduct.price);
  }
});

console.log(cartTotals)

const totalAmount = cartTotals.reduce((a, b) => a + b, 0);

console.log(totalAmount);

So specifically using the methods you want to use. You could do something like so. The main thing I change though is iterating the cart first and then using the find method to match the cart id to the product id.

const cart = [{
    _id: '624bc7fe0f91078261ab6529',
    qty: 1
  },
  {
    _id: '624bc8240f91078261ab6531',
    qty: 2
  }
]

const products = [{
    _id: '624bc7fe0f91078261ab6529',
    name: 'sample 1',
    price: 30,
    countInStock: 10
  },
  {
    _id: '624bc8240f91078261ab6531',
    name: 'sample 2',
    price: 10,
    countInStock: 4
  },
  {
    _id: '624bc1a50f91078261ab650d',
    name: 'sample 3',
    price: 15,
    countInStock: 1
  },
  {
    _id: '62562017645f1882e45adc32',
    name: 'sample 4',
    price: 20,
    countInStock: 7
  }
]

const cartTotals = [];
cart.forEach((product) => {
  const matchedProduct = products.find(element => element._id === product._id);
  if (matchedProduct) {
    cartTotals.push(product.qty * matchedProduct.price);
  }
});

console.log(cartTotals)

const totalAmount = cartTotals.reduce((a, b) => a + b, 0);

console.log(totalAmount);
放飞的风筝 2025-02-16 20:43:51

您可以使用这样的单个foreach来完成此操作:

let total = 0;
cartInfo.forEach(productInCart => {
  const product = products.find(productExtended => productExtended.id === productInCart.id);
  total += product.price * productInCart.qty;
});

但是我建议将产品的价格存储在Cartinfo中,这样,在计数总数时,您根本不需要访问产品

You can do it with a single forEach like this:

let total = 0;
cartInfo.forEach(productInCart => {
  const product = products.find(productExtended => productExtended.id === productInCart.id);
  total += product.price * productInCart.qty;
});

But I would suggest to store the product's price inside cartInfo, that way you will not need to access products at all when counting the total

情魔剑神 2025-02-16 20:43:51

尝试使用降低功能

const total = cartInfo.reduce((totalValue, currentCartItem) => {
  const foundProduct = products.find(product => product._id === currentCartItem._id);
  if (foundProduct) {
    totalValue += foundProduct.price * currentCartItem.qty
 }
}, 0);

Try using reduce function

const total = cartInfo.reduce((totalValue, currentCartItem) => {
  const foundProduct = products.find(product => product._id === currentCartItem._id);
  if (foundProduct) {
    totalValue += foundProduct.price * currentCartItem.qty
 }
}, 0);
归属感 2025-02-16 20:43:51

这是一个示例,您可以在其中获得每个项目的小计,然后总计:

const cartInfo = [
  {_id: '624bc7fe0f91078261ab6529', qty: 1},
  {_id: '624bc8240f91078261ab6531', qty: 2}
]

const products = [
  {_id: '624bc7fe0f91078261ab6529', name: 'sample 1', price: 30, countInStock: 10},
  {_id: '624bc8240f91078261ab6531', name: 'sample 2', price: 10, countInStock: 4},
  {_id: '624bc1a50f91078261ab650d', name: 'sample 3', price: 15, countInStock: 1},
  {_id: '62562017645f1882e45adc32', name: 'sample 4', price: 20, countInStock: 7}
]

let subtotals = cartInfo.map(({_id, qty}) => {
  return { _id, subtotal: qty * products.find(p => p._id === _id).price }
})

let total = subtotals.reduce((total, item) => item.subtotal + total, 0)

console.log('Subtotals:', subtotals)
console.log('Total:', total)

Here is an example where you can get the subtotal for each item and then the total:

const cartInfo = [
  {_id: '624bc7fe0f91078261ab6529', qty: 1},
  {_id: '624bc8240f91078261ab6531', qty: 2}
]

const products = [
  {_id: '624bc7fe0f91078261ab6529', name: 'sample 1', price: 30, countInStock: 10},
  {_id: '624bc8240f91078261ab6531', name: 'sample 2', price: 10, countInStock: 4},
  {_id: '624bc1a50f91078261ab650d', name: 'sample 3', price: 15, countInStock: 1},
  {_id: '62562017645f1882e45adc32', name: 'sample 4', price: 20, countInStock: 7}
]

let subtotals = cartInfo.map(({_id, qty}) => {
  return { _id, subtotal: qty * products.find(p => p._id === _id).price }
})

let total = subtotals.reduce((total, item) => item.subtotal + total, 0)

console.log('Subtotals:', subtotals)
console.log('Total:', total)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文