json - 我如何访问angular2中嵌套的json数据

标签 json angular

这是我的 app.component.ts

@Component({
  selector: 'my-app',
  template: `<h1>{{title}}</h1>
  {{test | json}}

  <div ngFor='let test of tests' style='border: solid 1px'>
    <div>
      <P>
        writer: {{test.A.B.C.D.writerid}} <br>
        content:{{test}}<br>
        write_date:{{test}}</P>
    </div>
  </div>
  `,
})

public test: any[] = [
 {
   'A': {
     'B': [{
       'C': {
         'D': [{
           'content': 'content_test1',
           'writedt': '2017-02-08 00:00:00',
           'writerid': 'writerid_test1'
          }, {
           'content': 'content_test2',
           'writedt': '2017-02-08 00:00:00',
           'writerid': 'writerid_test1'
          }, {
            'content': 'content_test3',
            'writedt': '2017-02-08 00:00:00',
            'writerid': 'writerid_test2'
         },  {
           'content': 'content_test4',
           'writedt': '2017-02-08 00:00:00',
           'writerid': 'writerid_test2'
         }]
       }
     }]
   }
 }
];

test.A.B.C.D.writerid 不工作 错误:无法读取未定义的属性“B” 我不明白为什么错误不是 A 而是 B 我如何访问 D 的内容或 writedt 或 writerid

最佳答案

首先,我假设您的模板中有一些拼写错误(例如 ngFor),并且该数组实际上称为 tests 但让我们忽略它。

我猜您想遍历 D 的数组。 无需对数据结构进行任何更改,您可以使用嵌套的 *ngFor:s 来完成。

所以首先你的数组应该命名为tests,而不是test。以及如何访问最内层数组,我们将首先遍历 tests 数组,然后遍历数组 B,最后遍历最内层数组 D。 所以你的模板看起来像这样:

  <div *ngFor="let test of tests">
    <div *ngFor="let x of test.A.B">
      <div *ngFor="let y of x.C.D; let i = index"> <h4>Content {{i+1}}</h4>
        {{y.content}}
        {{y.writedt | date}}
        {{y.writerid}}
      </div>
    </div>
  </div>

DEMO

关于json - 我如何访问angular2中嵌套的json数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43204434/

相关文章:

ios - Swift IAP 稍后从 json 响应中获取latest_receipt_info 值

angular - 从 Material Icon Registry 加载图标时出现 "<svg> tag not found"错误

html - Angular 2 Material 自定义 md-menu

javascript - 以表格格式显示来自 XML 和 JSON 的数据

javascript - 从 JSON 对象的内部深处获取信息

arrays - 过滤器以在 Angular js 中对 JSON 数据进行排序

node.js - 从 Angular 2 中使用 html-pdf 创建的 Node/express 后端接收文件

angular - 如何使用 headless 浏览器运行测试?

html - 如何使用选项卡显示特定用户的信息而不仅仅是第一个

javascript - 如何在Javascript中对Json数据进行排序?