Javascript减少了对象数组中的某些对象

时间:2018-04-16 00:40:13

标签: javascript arrays object dictionary reduce

我在计算对象值数组时遇到了一些问题...我下面的代码工作得很好,但如果我只想在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";

你知道,类似于此。我怎样才能实现这样的目标呢?

谢谢。

2 个答案:

答案 0 :(得分:3)

您可以使用filter()来完成此操作。 filter()返回一个数组,传递给它的函数返回true。这具有仅重新调整类型'

的项目的效果。



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)




答案 1 :(得分:1)

首先在reduce函数中添加条件。如果元素与条件不匹配,则只需先返回累加器而不进行修改。