0

I have an array with objects and I need to sum the prices from all these objects.

[{"name":"product1","value":3,"price":60},{"name":"product2","value":3,"price":12},{"name":"product3","value":3,"price":24},{"name":"product4","value":1,"price":16}]

I've tried map to get the prices only form the Array, but it doesn't work..

It's mee
  • 1
  • 1
  • 2
    Can you include the code that you tried? Maybe it just needs little adjustments. Also include an example of the desired output. – aerial Nov 18 '21 at 12:35
  • Welcome to SO. You might find reading the site [help section](https://stackoverflow.com/help) useful when it comes to [asking a good question](https://stackoverflow.com/help/how-to-ask), and this [question checklist](https://meta.stackoverflow.com/questions/260648/stack-overflow-question-checklist). Code that you have worked on to solve the problem should include a [mcve], and be included in your question. – Andy Nov 18 '21 at 12:36

1 Answers1

0

Well, you are gonna need a variable first. Then you iterate through all objects inside the array, adding the price to the variable.

var price = 0;

[
  { name: 'product1', value: 3, price: 60 },
  { name: 'product2', value: 3, price: 12 },
  { name: 'product3', value: 3, price: 24 },
  { name: 'product4', value: 1, price: 16 },
].forEach((val) => {
  price += val.price;
});

console.log(price);
pilchard
  • 12,414
  • 5
  • 11
  • 23
GoldenretriverYT
  • 3,043
  • 1
  • 9
  • 22
  • I have tried map already and it works fine only if it's written the way You wrote it so an array.forEach ... but I have this array in a variable like this ''' const products = [{"name":"Śledź w śmietanie 100 g/ 1 porcja","value":3,"price":60},{"name":"Pierogi z kapustą i grzybami/ 1 porcja","value":3,"price":12},{"name":"Paszteciki z mięsem / 1 porcja","value":3,"price":24},{"name":"Karp smażony 100 g/1 porcja","value":1,"price":16}]'''and when I try to use map on this variable it shows :Uncaught TypeError: products.forEach is not a function – It's mee Nov 18 '21 at 13:18
  • @It'smee then your problem is somewhere else. It works without a problem. Could it be that you are trying to access products outside the scope it is defined? – GoldenretriverYT Nov 18 '21 at 13:21
  • I don't think so. I'm taking this array straight from the HTML document object and attaching it to a variable and then use map on this variable. I tried this code in the browser console only. – It's mee Nov 18 '21 at 13:27