Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
94 views
in Technique[技术] by (71.8m points)

javascript - How to create array of objects dynamically in Angular 11?

I am trying to create array of objects dynamically in Angular. I have this segment of code:

 data:{title:any,date:any};
  arr:any=[]
  this.service.calendarBooking().subscribe((res: any) => {
      for (let i = 0; i < res.data.length; i++) {
        // Creating object from API Response
        this.data={title:res.data[i].name,date:res.data[i].date}
        // Pushing object to array
        this.arr.push(this.data)
      }
    })

When I am printing the array, the array responses like this:

0: {title: "spss", date: "2021-01-30"}
1: {title: "spss", date: "2021-01-29"}
2: {title: "spss", date: "2021-01-28"}

But when I am trying to access the indexes(arr[0],arr[1]) the response is undefined, length of arr is zero How to solve this issue"?

question from:https://stackoverflow.com/questions/65882676/how-to-create-array-of-objects-dynamically-in-angular-11

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

this.arr is different and the arr you have written below data:{title:any,date:any}; is different,

either push it to arr.push(this.data) or access like (this.arr[0] , this.arr[1])


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...