简体   繁体   English

在 Javascript 中循环对象值

[英]Looping through object values in Javascript

I have 3 objects.我有3个对象。

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.我试图将数量值加在一起,应该等于 13。我似乎无法掌握如何实际获得这些值。 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.要使用 Object.values,您需要引用每个索引。 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.您只需使用 reduce 循环遍历数组,您就可以在其中读取数量属性。

 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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