I have a list of objects and I need to loop through each object add all the "price" field to get the total value.
[
{
"_id":"61d167f9f5986df9dd291603",
"name":"test2",
"price":2000
},
{
"_id":"61d167f9f5986df9dd291602",
"name":"test3",
"price":4000
},
{
"_id":"61d167f9f5986df9dd291601",
"name":"test4",
"price":5000
}
]
I tried doing,
for(i in items){
let total = total + i.price;
}
console.log(total)
But dint work.
Try:
const items = [{"_id":"61d167f9f5986df9dd291603","name":"test2","price":2000},{"_id":"61d167f9f5986df9dd291602","name":"test3","price":4000},{"_id":"61d167f9f5986df9dd291601","name":"test4","price":5000}];
let total = 0;
for(let i = 0; i <= items.length - 1; i++) {
total += items[i].price
}
console.log(total)
Fetch this JSOn data into the List / ArrayList and using the for each loop traverse that list using object. Example - Suppose your data is stored in list whose object name is data int total = 0 for each list_data_type in data1 total = data1.price + total;