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

1
  • 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= [...] Commented Jun 5, 2020 at 20:36

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

2 Comments

i tried first one it is giving me result but not in order as receiving in original object. it is shuffling the order
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 to control the sort order when using keyvalue pipe.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.