Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript Convert Object to Array - because *ngFor does not supports iteration of object

Tags:

  • 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

like image 634
Ankit Maheshwari Avatar asked Jan 04 '17 07:01

Ankit Maheshwari


People also ask

How do you turn an object into an array?

To convert an object to an array you use one of three methods: Object. keys() , Object. values() , and Object. entries() .

How do I iterate an object in TypeScript?

Use let k: keyof T and a for-in loop to iterate objects when you know exactly what the keys will be. Be aware that any objects your function receives as parameters might have additional keys. Use Object. entries to iterate over the keys and values of any object.


2 Answers

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  
like image 158
Farooq Ahmed Khan Avatar answered Sep 20 '22 19:09

Farooq Ahmed Khan


Since Angular 6, there is now a keyvalue pipe operator. Simple do the following:

*ngFor="let item of objectList | keyvalue"  item.key # refers to the keys (134, 135...) in your example item.value # refers to the object for each key 
like image 45
henry74 Avatar answered Sep 18 '22 19:09

henry74