2

I want to display an object values to template in angular. but my object is dynamic so i do not know its keys. i also tried pipe keyvalues but that is not working for me. i tried one possible solution but not able to complete it.i am getting keys values as an array and object also but not able to parse in ng template here whats i have tried-

data=[
{'a':12,'b':34,'d':32,'w':3}
{'a':2,'b':4,'d':3,'w':23}
{'a':24,'b':24,'d':13,'w':63}
]
key_name=['a','b','d','w']

in html file i am trying to use *ngFor

<ion-row class="data-table data-table-row" *ngFor="let data of tableData">
<ion-col> {{data}}</ion-col>
</ion-row>

*****i am using ionic**** but data is giving [object][object] data is displaying when i am writing key name with it

{{data.a}}

Thanks

  • are you sure tableData is an array of objects ? if it's giving you [object][object] it appears you have 2 dimensional array, simple object should give you [object Object] and I hope where you declare array you meant to write tableData= [...] – ihor.eth Jun 05 '20 at 20:36

1 Answers1

2

You might have to use two *ngFor loops. Try the following

tableData = [
  {'a':12,'b':34,'d':32,'w':3},
  {'a':2,'b':4,'d':3,'w':23},
  {'a':24,'b':24,'d':13,'w':63}
]
<ng-container *ngFor="let data of tableData">    <!-- iterate the `tableData` array -->
  <ng-container *ngFor="let item of data | keyvalue">    <!-- iterate the object in element of the array -->
    {{ item.key }} : {{ item.value }}
  </ng-container>
</ng-container>

Or if you do not want to iterate every property of the object, you could use json pipe

<ng-container *ngFor="let data of tableData">    <!-- iterate the `tableData` array -->
  {{ data | json }}
</ng-container>

Or if you still wish to use the key_name array to access the properties of the object, you could try the following

<ng-container *ngFor="let data of tableData">    <!-- iterate the `tableData` array -->
  <ng-container *ngFor="let key of key_name">    <!-- iterate the `key_name` array -->
    {{ key }} : {{ data[key] }}
  </ng-container>
</ng-container>
ruth
  • 29,535
  • 4
  • 30
  • 57
  • i tried first one it is giving me result but not in order as receiving in original object. it is shuffling the order – Chandra Verma Jun 05 '20 at 20:44
  • Thats because the `keyvalue` pipe sorts the items by `key` by default. You have 2 options. Either use the 3rd variant of the answer where you supply an external array of keys to access the properties or see [here](https://stackoverflow.com/q/52793944/6513921) to control the sort order when using `keyvalue` pipe. – ruth Jun 05 '20 at 20:46