2

The array consists of a key and value pair of objects.i want iterate through to fetch key and values of object.

var arr = [{fruit: banana},{color: red},{city: London},{count: 10},{price: 100$}];

i tried using keyvalue pipe

<div class="bx--row" *ngFor="let obj of arr | keyvalue; let i = index;">
     <span class="bx--col-xs-5 bx--col-md-5"> {{obj.key}} :</span>
     <span class="bx--col-xs-5 bx--col-md-5">{{obj.value}} </span>
</div>

Expected result:

fruit : banana
color: red
city: London
count : 10
price : 100$
New123
  • 219
  • 1
  • 4
  • 13
  • Does this answer your question? [access key and value of object using \*ngFor](https://stackoverflow.com/questions/35534959/access-key-and-value-of-object-using-ngfor) – Ajit Soman Jun 04 '20 at 10:10

2 Answers2

3

You might need two *ngFor directives. Try the following

<div class="bx--row" *ngFor="let obj of arr; let i = index;">
  <ng-container *ngFor="let item of obj | keyvalue">
    <span class="bx--col-xs-5 bx--col-md-5"> {{item.key}} :</span>
    <span class="bx--col-xs-5 bx--col-md-5">{{item.value}} </span>
  <ng-container>
</div>

Or you could merge the individual objects to a single object in the controller and iterate it with a single *ngFor.

Controller

const arr = [{fruit: 'banana'},{color: 'red'},{city: 'London'},{count: 10},{price: '100$'}];
const obj = Object.assign({}, ...arr)

Template

<div class="bx--row" *ngFor="let item of obj | keyvalue; let i = index;">
  <span class="bx--col-xs-5 bx--col-md-5"> {{item.key}} :</span>
  <span class="bx--col-xs-5 bx--col-md-5">{{item.value}} </span>
</div>
ruth
  • 29,535
  • 4
  • 30
  • 57
0

You can do it like this

in html

<div class="bx--row" *ngFor="let obj of arr">
     <span class="bx--col-xs-5 bx--col-md-5"> {{objectKeys(obj)}} :</span>
     <span class="bx--col-xs-5 bx--col-md-5">{{obj[objectKeys(obj)]}} </span>
</div>

in ts

objectKeys(obj){
 return Object.keys(obj)[0];
}
Shlok Nangia
  • 2,355
  • 3
  • 16
  • 24