我试图找到索引值项目附在item-0, item-1, item-2, item-3
内,如果有人可以帮助解决这个问题。
json:
"ingredients": {
"item-0": {
"amount": "30",
"measurement": "g",
"item": "455"
},
"item-1": {
"amount": "10",
"measurement": "oz",
"item": "455"
}
"item-2": {
"amount": "1",
"measurement": "lb",
"item": "455"
}
"item-3": {
"amount": "3",
"measurement": "tsp",
"item": "455"
}
},'
角:
<ul *ngFor="let item of recipe.ingredients; let i = index;">
<li>{{recipe[i].amount}}</li>
<li>{{recipe[i].measurement}}</li>
<li>{{recipe[i].item}}</li>
</ul>
我只能返回索引值作为一个数字,但我需要返回它作为item-[i]
。
const keys = Object.keys(ingredients);
console.log(keys); // [ 'item-1', 'item-2', 'item-3']
// Getting the numbers from each key
const numbers = keys.map((key) => key.split('-')[1]);
console.log(numbers); // ['1', '2', '3'];
可以使用内置的Pipe KeyValue来迭代对象:https://angular.io/api/common/KeyValuePipe。
然后您可以使用item.key
(获取'item-1', 'item-2', 'item-3')和item.value
来访问数据:
<ul *ngFor="let item of recipe.ingredients | keyvalue">
<li>{{item.key}}</li>
<li>{{item.value.amount}}</li>
<li>{{item.value.measurement}}</li>
<li>{{item.value.item}}</li>
</ul>
下面是工作示例:https://stackblitz.com/edit/angular-ivy-uavxyr?file=src%2Fapp%2Fapp.component.html