[英]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.该数组由对象的键和值对组成。我想遍历以获取 object 的键和值。
var arr = [{fruit: banana},{color: red},{city: London},{count: 10},{price: 100$}];
i tried using keyvalue pipe我尝试使用键值 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.您可能需要两个*ngFor
指令。 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 中的单个 object 并使用单个*ngFor
进行迭代。
Controller 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在 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在 ts
objectKeys(obj){
return Object.keys(obj)[0];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.