0

I have 3 objects.

obj([]);
obj([{name:'Jeans', quantity:5}]);
obj([{name:'Jeans-M-B', quantity:1},{name:'Jeans-S-R', quantity:7}]);

I am trying to add the quantity values together which should equal to 13. I can't seem to grasp on how to actually get the values. When I tried the code below, it just gives me the objects themselves instead of their values.

function obj(itemsObj) {

  var obj = Object.values(itemsObj);
  console.log(obj.quantity);
}
  • Object.values expects an object and you are passing in an array? – epascarello Dec 30 '19 at 16:35
  • Does this answer your question? [Better way to sum a property value in an array](https://stackoverflow.com/questions/23247859/better-way-to-sum-a-property-value-in-an-array) – Taplar Dec 30 '19 at 16:41

2 Answers2

0

You can reduce the object's quantities to their sum:

function quantities(obj) {
  return obj.reduce(function(acc, curr) {
    return acc + curr["quantity"]
  }, 0)
}

t = [{name:'Jeans-M-B', quantity:1},{name:'Jeans-S-R', quantity:7}];
console.log(quantities(t))
Corylus
  • 736
  • 5
  • 16
  • In julia I would write `reduce(+, map(x->x["quantity"], obj))` which feels very natural to me. But you are right, in js it is much simpler without the map. – Corylus Dec 30 '19 at 16:44
0

you are trying to pass an array into something that expects an object. To iuse Object.values, you would need to reference each index. In your case, you do not need to use it. You just loop over the array with reduce where you can read the quantity property.

function getTotal (items) {
  return items.reduce( function (cnt, item) {
    return cnt + item.quantity
  }, 0)
}

/*
const getTotal = items =>
  items.reduce(
    (cnt, item) => cnt + item.quantity
  , 0)
*/

var total = getTotal([{name:'Jeans-M-B', quantity:1},{name:'Jeans-S-R', quantity:7}]);

console.log(total)
epascarello
  • 204,599
  • 20
  • 195
  • 236