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

Angular中如何在select下拉框遍历嵌套数组展示数据?

解决Angular Select下拉框展示嵌套Currencies数组的问题

你现在遇到的问题是allData里的每个元素都是包含currencies数组的国家对象,直接用*ngFor="let currency of allData"去取currency[0].name行不通——因为你需要遍历的是每个国家里的currencies子数组,而不是国家数组本身。而且直接这么写还会出现重复的货币(比如多个国家用欧元),所以我们可以先把所有货币提取出来并去重,再渲染到下拉框里。

第一步:在组件里处理数据,提取并去重货币列表

假设你已经通过HTTP请求获取到了目标API返回的国家数据(存在countries变量里),你可以这样处理:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-currency-select',
  templateUrl: './currency-select.component.html',
  styleUrls: ['./currency-select.component.css']
})
export class CurrencySelectComponent implements OnInit {
  selected: string;
  countries: any[] = [];
  uniqueCurrencies: any[] = [];

  constructor(private http: HttpClient) { }

  ngOnInit(): void {
    this.http.get('https://restcountries.eu/rest/v2/all').subscribe((data: any[]) => {
      this.countries = data;
      // 提取所有货币并去重
      const currencyMap = new Map();
      this.countries.forEach(country => {
        country.currencies.forEach(currency => {
          // 用货币代码作为唯一标识去重
          if (!currencyMap.has(currency.code)) {
            currencyMap.set(currency.code, currency);
          }
        });
      });
      // 将Map转为数组
      this.uniqueCurrencies = Array.from(currencyMap.values());
    });
  }
}

第二步:修改模板中的Select下拉框

现在你可以直接遍历处理好的uniqueCurrencies数组,不用再处理嵌套结构了:

<select class="form-control-custom" [(ngModel)]="selected" placeholder="Filter Category By">
  <option>Get Countries By Currency Name</option>
  <option *ngFor="let currency of uniqueCurrencies;" [value]="currency.code">
    {{currency.name}} ({{currency.code}})
  </option>
</select>

补充说明

  • 用Map存储货币是为了利用货币代码作为唯一标识去重,避免下拉框里出现重复的货币选项
  • 通过嵌套循环将嵌套的currencies数组从每个国家对象里提取出来,整合成一个扁平化的数组,这样*ngFor就能直接遍历了
  • 模板里的[value]绑定了货币代码,方便后续根据选中的货币去筛选国家(如果有这个需求的话)

如果不需要去重,只是想展示所有国家的所有货币(包括重复项),可以直接生成扁平化数组:

// 不做去重的情况
this.uniqueCurrencies = this.countries.flatMap(country => country.currencies);

模板里的遍历逻辑保持不变即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:52:07