代码之家  ›  专栏  ›  技术社区  ›  Tom

多个foreach循环可能存在性能问题

  •  0
  • Tom  · 技术社区  · 4 年前

    我正在尝试从后端服务读取产品,并将其显示在 angular 前端。我已经声明了一组产品,其中包含翻译所需的密钥。我正在根据后端服务返回的代码进行匹配 代码是有效的,但是我认为这不是一种有效的方法,因为我使用了两个for循环。有人能提出一个更好的方法吗

         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) => {
                products.forEach((pro) =>{
                this.products1.forEach((pro1) =>{
                  if(pro.code === pro1.value){
                    pro.name = pro1.label;
                  }
                });
              });
    
              this.products = products.map((product) => ({ label: product.name, value: product.code }));;
              this.products.push({ label: 'Other', value: 'other' });
            })
          )
          .subscribe();
          
    
    0 回复  |  直到 4 年前
        1
  •  0
  •   abhishek sahu    4 年前

    这是一个简单的代码,只需要一个循环,而不需要嵌套forEach循环。

    let products1Map = {}
    this.products1.forEach((pro1) => {
        products1Map[pro1.value] = pro1.name;
    });
    
    this.products = products.map((product) => ({
        label: products1Map[product.code] ? products1Map[product.code] : product.name,
        value: product.code
    }));;
    this.products.push({
    label: 'Other',
    value: 'other'
    });
    })
    
        2
  •  0
  •   rfgsantos    4 年前

    你考虑过使用地图吗?

    https://howtodoinjava.com/typescript/maps/

    products1: Map<string, string> = new Map([
            ['BASESPECIALITY', 'common.base-metal'].....
        ]);
        
        this.referenceStore
          .getReference('products')
          .pipe(
            first(),
            tap((products) => {
              this.products = products.map((product) => ({ label: products1.get(product.code), value: product.code }));
              this.products.push({ label: 'Other', value: 'other' });
            })
          )
          .subscribe();