简体   繁体   中英

How to iterate an array of objects?

I got undefined when I mapped my array of objects, this my component.ts :

availableHistorics: Array<AvailableHistoric> = new Array<AvailableHistoric>();

ngOnInit() {
this.getAvailableHistorics();
}
getAvailableHistorics(){
 this.service.getAvailableHistorics().subscribe(data => {this.availableHistorics.push(data);
 console.log(this.availableHistorics.map(item => item.keyword))
});}

This is my class:

export class AvailableHistoric {
id : String
keyword : String
nameToDisplay : String}

This is the service:

export class ProductService {
 private baseUrl = 'http://localhost:8081/products';
 constructor(private http: HttpClient) { }
   getAvailableHistorics() : Observable <AvailableHistoric>{
    return this.http.get<AvailableHistoric>(this.baseUrl + 
 "/getAvailableHistorics")}}

This is the array I have:

[
{
    "_id": null,
    "keyword": "keyword1",
    "nameToDisplay": "name1"
},
{
    "_id": null,
    "keyword": "keyword2",
    "nameToDisplay": "name2"
},
{
    "_id": null,
    "keyword": "keyword3",
    "nameToDisplay": "name3"
}]

I want to get a list like that: ["keyword1","keyword2", "keyword3"] Is there a problem with my code?

You are pushing the whole array to your availableHistorics list, so what you get is a nested array. Guy Incognito is right. You have to assign data to this.availableHistorics .

I think the data you received is an array. And you are pushing it to an array. So the first element of an array is that array. eg:

 let arr = []; let data = [1, 2, 3]; arr.push( data ) console.log(arr )

One solution is to replace the array

 let arr = []; let data = [1, 2, 3]; arr = data; console.log(arr )

A better solution is to use destructoring.

 let arr = []; let data = [1, 2, 3]; arr.push(...data ) console.log(arr )

Read more about destructoring on MDN

PS: In your code this would be:

this.availableHistorics.push(...data)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM