简体   繁体   English

Angular - 显示来自 HTML 中的 2 个 JSON 的数据

[英]Angular - Display data from 2 JSON in HTML

I'm having trouble displaying data from 2 interconnected JSON in Angular.我无法在 Angular 中显示来自 2 个互连的 JSON 的数据。

First JSON:第一个 JSON:

member = [
  { id: 1, name: 'shinta'},
  { id: 2, name: 'rahma'},
  { id: 3, name: 'john'}
]

Second JSON:第二个 JSON:

nest = [
  {id: 1, amount: 2000, userid: 1},
  {id: 2, amount: 3000, userid: 2}, 
  {id: 3, amount: 5000, userid: 2},
  {id: 4, amount: 1500, userid: 1},
  {id: 5, amount: 2200, userid: 1},
  {id: 6, amount: 12500, userid: 1},
  {id: 7, amount: 7000, userid: 2}, 
  {id: 8, amount: 8300, userid: 3}, 
  {id: 9, amount: 2800, userid: 3},
  {id: 10, amount: 9500, userid: 3}
]

How to view/bind data in HTML?如何查看/绑定 HTML 中的数据?

<ul *ngFor="let item of memberData, let i = index">
  <li>{{ item.name }} <span>*this to view sum of user amount*</span></li>
</ul>

Please guide me to solve this problem.请指导我解决这个问题。 Thank you.谢谢你。

  1. Use .map() to create new array with:使用.map()创建新数组:
  • Duplicate object element of members (via ...x ) members的重复 object 元素(通过...x
  • New field: totalAmount with .reduce() to perform aggregate sum.新字段: totalAmount和 .reduce .reduce()来执行汇总。
this.memberData = this.member.map((x) => ({
  ...x,
  totalAmount: this.nest
    .filter((y) => y.userid == x.id)
    .reduce((total: number, current) => (total += current.amount), 0),
}));
<ul *ngFor="let item of memberData; let i = index">
  <li>
    {{ item.name }} <span>{{ item.totalAmount }}</span>
  </li>
</ul>

Demo on StackBlitz StackBlitz 上的演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM