You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多重foreach循环的潜在性能问题:Angular前端后端产品数据映射优化方案咨询

Optimizing Product Label Matching in Angular

Hey there! Your current implementation works, but those nested forEach loops lead to O(n*m) time complexity—something that'll get noticeably slower as either product list grows. Let's fix this with a Map for constant-time lookups, which will make the code cleaner, faster, and easier to maintain.

The Better Approach: Use a Map for Lookups

Instead of looping through both arrays every time, we'll first convert your products1 array into a key-value Map where the key is the product code (value field) and the value is the translation label (label field). This lets us look up the correct label for any backend product in O(1) time.

Here's the refactored code:

products: Choice[];
products1: Choice[] = [
  { label: 'common.base-metal', value: 'BASESPECIALITY' },
  { label: 'common.crop-nutrient', value: 'CROPNUTRIENT' },
  { label: 'common.iron-ore', value: 'IRONORE' },
  { label: 'common.metal-coal', value: 'METCOAL' },
  { label: 'common.precious-metals', value: 'PRECIOUS' },
  { label: 'common.shipping', value: 'SHIPPING' },
  { label: 'common.thermal-coal', value: 'THERMALCOAL' },
  { label: 'legal-forms.OTHER', value: 'other' }
];

this.referenceStore
  .getReference('products')
  .pipe(
    first(),
    tap((products) => {
      // Create a Map for fast label lookups
      const productLabelMap = new Map(this.products1.map(pro1 => [pro1.value, pro1.label]));

      // Update each product's name with a single loop
      products.forEach(pro => {
        pro.name = productLabelMap.get(pro.code);
      });

      // Transform and add the "Other" option (note: "other" is already in products1, so you could skip this if it's returned by the backend)
      this.products = products.map(product => ({ label: product.name, value: product.code }));
      this.products.push({ label: 'Other', value: 'other' });
    })
  )
  .subscribe();

Why This Works Better

  • Time Complexity: From O(n*m) (nested loops) to O(n + m) (one loop to build the Map, one loop to update products). This is a huge improvement when dealing with larger datasets.
  • Readability: The intent of looking up labels by product code is immediately clear, whereas nested loops can be harder to parse at a glance.
  • Maintainability: If you ever need to add/remove product types, you only modify the products1 array—no need to adjust loop logic.

Small Optional Improvement

Since your products1 already includes the "other" entry, you could skip the manual push if the backend doesn't return it, and instead filter/map products1 alongside the backend data. But that's up to your specific use case!

内容的提问来源于stack exchange,提问作者Tom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 19:37:43