简体   繁体   中英

Looping through object values in Javascript

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);
}

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM