简体   繁体   中英

Iterate through array of objects using *ngFor of angular

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$

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>

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];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM