In my JSON file, I have an array containing 5 people. Each person in the array has a list of items associated with them. In my HTML code, I am using *ngFor to iterate over the people and display their names. Additionally, I want to display the total sum of the prices of all the items associated with each person. To calculate the total price of all the items for each person, I have a function in my TypeScript code. The total prices are then displayed in the console.
The issue I am encountering is that the current implementation in my TypeScript file involves looping through the list of people twice. This means that I am iterating over the people in my HTML using *ngFor and within this loop, calling the function getTotal(), which itself loops through the people again. Ideally, I would like to only loop through the people once.
JSON Object:
"persons":[
{
"name": "Peter",
"items": [
{
"name": "pen",
"price": 1.50
},
{
"name": "paper",
"price": 2.00
}
]
},
{
"name": "Maria",
"items": [
{
"name": "scissors",
"price": 4.00
},
{
"name": "stickers",
"price": 3.00
}
]
}
// three more persons
]
HTML Code:
<div *ngFor="let person of persons"> <!-- Looping through the persons here -->
<p>{{person.name}}</p>
<p>Total <span>{{getTotal()}}</span></p> <!-- Calling the function here, leading to another loop through persons -->
</div>
TypeScript Code:
getTotal() {
for(let person of this.persons){
let total = 0;
for(let item of person.items){
total += item.price;
}
console.log(total);
}
}
Question: The current setup involves unnecessary duplication where I am looping through the people in both the HTML code using *ngFor and the TypeScript code within getTotal(). Is there a way to access the current element being iterated over in *ngFor without needing the initial loop in getTotal()? Can this be achieved or is it not possible?