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

如何将产品数据筛选并分组到两个类变量(categoryOne、categoryTwo)中?

实现产品数据筛选分组

1. 声明类变量

在组件类中先定义用于存储分组数据的变量:

// 组件类内部
categoryOne: any[] = [];
categoryTwo: any[] = [];

2. 修改getProducts方法处理数据

在订阅产品数据后,使用filter方法按category字段筛选数据,分别赋值给对应的类变量。如果需要按order字段排序,可追加sort方法保证展示顺序:

getProducts() {
  this.productService.getProducts().subscribe(products => {
    this.products = products;
    
    // 筛选categoryone分组并按order升序排序
    this.categoryOne = products
      .filter(product => product.category === 'categoryone')
      .sort((a, b) => a.order - b.order);
    
    // 筛选categorytwo分组并按order升序排序
    this.categoryTwo = products
      .filter(product => product.category === 'categorytwo')
      .sort((a, b) => a.order - b.order);
  });
}

3. 在模板中展示分组数据

使用Angular的*ngFor指令遍历分组后的变量,渲染产品信息:

<!-- 渲染Category One产品 -->
<h3>Category One</h3>
<div class="product-item" *ngFor="let product of categoryOne">
  <p><strong>Code:</strong> {{ product.code }}</p>
  <p><strong>Order:</strong> {{ product.order }}</p>
  <p><strong>Price:</strong> {{ product.price }}</p>
  <p><strong>Description:</strong> {{ product.description || '无描述' }}</p>
</div>

<!-- 渲染Category Two产品 -->
<h3>Category Two</h3>
<div class="product-item" *ngFor="let product of categoryTwo">
  <p><strong>Code:</strong> {{ product.code }}</p>
  <p><strong>Order:</strong> {{ product.order }}</p>
  <p><strong>Price:</strong> {{ product.price }}</p>
  <p><strong>Description:</strong> {{ product.description || '无描述' }}</p>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 14:10:37