How to iterate two array at same time using ngFor in angular?

Viewed 8280

I have to array objects as payload which comes from node.js, and i store it in different variables and iterate but *ngFor iterate only first loop not second so how to itterate both at same div status.component.html

<div *ngFor="let payload1 of payload1;let payload2 of payload2;">
  <h4>{{payload2.username}}</h4>
  <h4>{{payload1.date}}</h4>
</div>

status.component.ts

payload1 = [];
payload2 = [];

ngOnInit() {
  this.statusService.getStatusDetails(this.statusObj).subscribe(
    (data) => {
      if(data.status == 26){
        this.payload1 = data.payload[0];
        this.payload2 = data.payload[1];
      }
    }
 );
}
2 Answers

I think this should work if your payloads are the same length and ordered to match (which your question seems to imply it does)

<div *ngFor="let p of payload1;let i = index">
  <h4>{{payload2[i].username}}</h4>
  <h4>{{payload1[i].date}}</h4>
</div>

Why not make a single array out of that ?

payload = [];
ngOnInit() {
  this.statusService.getStatusDetails(this.statusObj).subscribe(
    (data) => {
      if(data.status == 26){
        this.payload = data.payload[0]
          .map((item, index) => ({ ...item, ...data.payload[1][index] }));
      }
    }
 );
}

Snippet proving it works :

const d1 = [
  { id: 0 },
  { id: 1 },
];

const d2 = [
  { name: '0' },
  { name: '1' },
];

const d3 = d1.map((item, index) => ({ ...item, ...d2[index] }));

console.log(d3);

You can even build this merged payload if the arrays aren't the same length.

const d1 = [
  { id: 0 },
  { id: 1 },
];

const d2 = [
  { name: '0' },
  { name: '1' },
  { name: '2' },
];

const longest = d1.length > d2.length ? d1 : d2;
const shortest = d1.length <= d2.length ? d1 : d2;

const d3 = longest.map((item, index) => ({ ...item, ...shortest[index] }));

console.log(d3);

Angular version :

payload = [];
ngOnInit() {
  this.statusService.getStatusDetails(this.statusObj).subscribe(
    (data) => {
      if(data.status == 26){

        const longest = data.payload[0].length > data.payload[1].length ? 
          data.payload[0] : data.payload[1];
        const shortest = data.payload[0].length <= data.payload[1].length ? 
          data.payload[0] : data.payload[1];

        this.payload = longest
          .map((item, index) => ({ ...item, ...shortest[index] }));
      }
    }
 );
}
Related