Home > Software design >  perform operation on an array and display it in array form in ts
perform operation on an array and display it in array form in ts

Time:08-30

imageData: any = [];
image_name: any = [];
payload: any = [];
this.imageData = ['https://images/3.jfif', 'https://images/4.jfif', 'https://images/1.jfif'];
this.image_name = [];
for (var i = 0; i < this.imageData.length; i  ) {
  this.image_name = this.imageData[i].split('/').pop();
  console.log(this.imageData[i])
  console.log(this.image_name);
  this.payload = [{
    "link": this.imageData[i],
    "name": this.image_name
  }]
  console.log(payload)
}

currently I am only getting result for the last item,

 [{
        "link": "https://images/1.jfif',
        "name": '1.jfif'}
    ]

this is how i want the array to be

[{
  "link":"https://images/3.jfif',
"name": '3.jfif'},
{
  "link":"https://images/4.jfif',
"name": '4.jfif'},
  {
    "link": "https://images/1.jfif',
    "name": '1.jfif'}
]

in html, this is how i am calling it

<div  *ngFor="let img of payload" >
        <img  src="{{img.link}}" />
       <div> {{img.name}}</div
</div

please suggest a way to print payload as an array form

CodePudding user response:

in your for loop you're assigning data to the payload array. so that at the last for loop iteration you assign an array of the last element[this.payload = [{ "link": this.imageData[i], "name": this.image_name }]] to your payload array. you just need to push[this.payload.push({ "link": this.imageData[i], "name": this.image_name })] your element to payload array at every iteration.

imageData: any = [];
image_name: any = [];
payload: any = [];
this.imageData = ['https://images/3.jfif', 'https://images/4.jfif', 'https://images/1.jfif'];
this.image_name = [];
for (var i = 0; i < this.imageData.length; i  ) {
  this.image_name = this.imageData[i].split('/').pop();
  console.log(this.imageData[i])
  console.log(this.image_name);
  this.payload.push({
    "link": this.imageData[i],
    "name": this.image_name
  })
  console.log(payload)
}
  • Related