-2
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 class="slide" *ngFor="let img of payload" >
        <img class="images" src="{{img.link}}" />
       <div> {{img.name}}</div
</div

please suggest a way to print payload as an array form

dev12321
  • 3
  • 3
  • 1
    You're redeclaring `payload` on each iteration of the loop, `let payload = [{...`, you should instead be pushing to the `payload` array declared before the loop `payload.push({ "link": this.imageData[i], "name": this.image_name });`. But your assignment to `this.image_name` is also odd since you reassign on every iteration, it looks like you need to read up on [variable scope](https://stackoverflow.com/questions/70177862/what-is-difference-between-let-const-and-var-in-case-of-variable-shadowing-re). – pilchard Aug 27 '22 at 21:46

1 Answers1

0

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)
}
Exception
  • 571
  • 1
  • 3
  • 15