Typescript Convert Object to Array - because *ngFo

2019-02-11 00:37发布

  • I don't want to use for loop to convert Object to Array like this! If doubled the process and slow down the performance of app (I'm using Ionic2 and Typescript, with Firebase)

    for(let key in data) { array.push(value); }

Is there any solution to iterate object itself(shown in picture attached) using *ngFor.

Or I can convert this Object(shown in picture attached) to Array, so that can be iterable in *ngFor.

enter image description here

2条回答
对你真心纯属浪费
2楼-- · 2019-02-11 00:55

Adding toArray() on the pipe worked for me.

// Import toArray function
import { toArray } from 'rxjs/operators';

// Generic function to consume API
searchObjects(term: string): Observable<theObject[]> {
  requestUrl = this.url + term;
  return this.http.get<theObject[]>(requestUrl, httpOptions).pipe(
      // convert object to array
      toArray<theObject>()
  );
}

查看更多
在下西门庆
3楼-- · 2019-02-11 01:17

You can use Object.keys(obj) to get named indexes. This will return an array structure which you can use/customize further. A sample use to iterate over object values may look like this

var persons = { 
    john: { age: 23, year:2010},
    jack: { age: 22, year:2011},
    jenny: { age: 21, year:2012}
}

Getting an iterator

var resultArray = Object.keys(persons).map(function(personNamedIndex){
    let person = persons[personNamedIndex];
    // do something with person
    return person;
});

// you have resultArray having iterated objects 
查看更多
登录 后发表回答