0

I'm having trouble displaying data from 2 interconnected JSON in Angular.

First JSON:

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

Second 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?

<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
  • you are rendering data on memberData where is the memberData in your ts? add that snippet as well Commented Mar 6, 2022 at 7:17

1 Answer 1

1
  1. Use .map() to create new array with:
  • Duplicate object element of members (via ...x)
  • New field: totalAmount with .reduce() to perform aggregate sum.
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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. now my problem solve because you. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.