The Array
has the method reduce that is very often used in cases like this one.
It takes as the first parameter a function which will be called for every element in the array and a second, but optional, argument that will be the initial value.
So, in your case, you could do something like this:
const sum = Data.reduce((accumulator, obj) => accumulator + obj.price, 0)
The first time it's called the value of accumulator
is 0, the next times the value of the accumulator will be the return value of the previous call of the function```
so it will work as the following:
// first call
// accumulator = 0
// obj = {id:0,name:”lamp”,price: 5}
return accumulator + obj.price
// second call
// accumulator = 5
// obj = {id:1, name:”bed”, price:10}
return accumulator + obj.price
// third call
// accumulator = 15
// obj = {id:2,name: “shelf”, price 3}
return accumulator + obj.price
// now accumulator = 18