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

Angular中如何遍历嵌套JSON对象并在模板用*ngFor渲染

在Angular中遍历嵌套JSON对象的解决方案

假设你的client.json结构如下:

{
  "T001": { "name": "admin", "desc": "主隧道" },
  "T002": { "name": "guest", "desc": "访客隧道" }
}

步骤1:将嵌套对象转换为可遍历的数组

在组件中,利用Object.entries()方法把JSON对象的键值对转为数组,这样就能用*ngFor遍历了。

直接导入JSON文件的情况

import { Component, OnInit } from '@angular/core';
// 导入本地JSON文件
import clientData from './client.json';

@Component({
  selector: 'app-tunnel-list',
  templateUrl: './tunnel-list.component.html'
})
export class TunnelListComponent implements OnInit {
  // 存储键值对数组,类型为[隧道ID, 属性对象]
  tunnelEntries: [string, any][] = [];

  ngOnInit(): void {
    // 转换为可遍历的数组
    this.tunnelEntries = Object.entries(clientData);
  }
}

通过HTTP读取JSON文件的情况

如果是从assets目录读取,用HttpClient请求后再转换:

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

@Component({
  selector: 'app-tunnel-list',
  templateUrl: './tunnel-list.component.html'
})
export class TunnelListComponent implements OnInit {
  tunnelEntries: [string, any][] = [];

  constructor(private http: HttpClient) {}

  ngOnInit(): void {
    this.http.get('/assets/client.json').subscribe((data: any) => {
      this.tunnelEntries = Object.entries(data);
    });
  }
}

步骤2:在HTML模板中遍历渲染

直接使用*ngFor遍历转换后的数组,通过索引获取隧道ID和属性:

<div *ngFor="let entry of tunnelEntries">
  Tunnel: {{ entry[0] }},Name: {{ entry[1].name }}
</div>

可选:转换为更清晰的对象结构

如果觉得数组索引不够直观,可以把键值对映射为结构化对象:

// 在组件的ngOnInit中替换转换逻辑
this.tunnelEntries = Object.entries(clientData).map(([tunnelId, props]) => ({
  tunnelId,
  ...props
}));

对应的模板代码可以写成:

<div *ngFor="let tunnel of tunnelEntries">
  Tunnel: {{ tunnel.tunnelId }},Name: {{ tunnel.name }}
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 18:01:23