-1

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.

Sai Krishnadas
  • 2,863
  • 9
  • 36
  • 69
  • 2
    Your `total` is scoped to your inner loop. Move it's defination outside. – Keith Jan 02 '22 at 10:00
  • If you log `i` what information does that give you? – Andy Jan 02 '22 at 10:01
  • _Didn't work_ is not very helpful. May be more helpful to be more descriptive. Change the keyword `in` to `of` and declare `total` before the loop. – PeterKA Jan 02 '22 at 10:02
  • 1
    Oh, and just noticed you maybe wanted `of` and not `in` – Keith Jan 02 '22 at 10:04
  • This is an excellent example of when to use [`Array.prototype.reduce`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce) – Paul S. Jan 02 '22 at 10:08

2 Answers2

2

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)
-1

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;