[英]Javascript reduce for certain objects within an array of objects
我在计算对象值数组时遇到了一个小问题...我下面的代码工作正常,但是如果我只想在reduce函数中定位某些对象怎么办?
基本上,类似SQL WHERE函数,所以
newcost = Number((cart.map(item => (item.cost * item.amm)).reduce((prev, next) => Number(prev) + Number(next))).toFixed(2));
将会
newcost = Number((cart.map(item => (item.cost * item.amm)).reduce((prev, next) => Number(prev) + Number(next))).toFixed(2)) WHERE item.type === "c";
您知道,与此类似。 我怎样才能实现这样的目标?
谢谢。
这是使用filter()
。 filter()
返回一个数组,传递给它的函数返回true。 这具有仅重新调整类型'c'的项目的效果。
var cart = [ {type:'c', cost:20.00, amm: 10}, {type:'d', cost:20.00, amm: 1}, {type:'d', cost:20.00, amm: 2}, {type:'c', cost:1.00, amm: 5}, {type:'a', cost:20.00, amm: 7}, ] let newcost = cart.filter(i => i.type === 'c') // only c type items .map(item => item.cost * item.amm) .reduce((prev, next) => prev + next) .toFixed(2); console.log(newcost)
另外,您也没有要求,但是map()
调用是多余的-您并不是真正需要它,它会导致数据中的额外循环(您也可以在reduce()
进行测试,而忽略filter()
尽管这可能会开始影响可读性):
var cart = [ {type:'c', cost:20.00, amm: 10}, {type:'d', cost:20.00, amm: 1}, {type:'d', cost:20.00, amm: 2}, {type:'c', cost:1.00, amm: 5}, {type:'a', cost:20.00, amm: 7}, ] let newcost = cart.filter(i => i.type === 'c') .reduce((prev, next) => prev + next.cost * next.amm, 0) .toFixed(2); console.log(newcost)
在reduce函数中先添加条件。 如果该元素与您的条件不匹配,则只需先返回累加器即可,而无需对其进行修改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.