I am trying to find the index value with item- attached within item-0, item-1, item-2, item-3
, if anyone can help with a solution for this.
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"
}
},'
angular:
<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>
I can only return the index value as a number but I would need return it as 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'];
You can use the builtin Pipe KeyValue to iterate on an Object: https://angular.io/api/common/KeyValuePipe .
Then you can use item.key
(to get 'item-1', 'item-2', 'item-3') and item.value
to access the data:
<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>
Here is the working example: https://stackblitz.com/edit/angular-ivy-uavxyr?file=src%2Fapp%2Fapp.component.html
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.