【问题标题】:Javascript reduce for certain objects within an array of objectsJavascript减少对象数组中的某些对象
【发布时间】:2018-09-25 15:42:47
【问题描述】:

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

你知道,类似的事情。我怎样才能实现这样的目标?

谢谢。

【问题讨论】:

  • 你可以在两者之间加上一个.filterx.map().filter(...).reduce(...)
  • @georg 会是什么样子?

标签: javascript arrays object dictionary reduce


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    下面是使用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)

    【讨论】:

      猜你喜欢
      • 2018-09-01
      • 1970-01-01
      • 2019-05-18
      • 2021-04-02
      • 2017-05-09
      • 2018-07-18
      • 2019-03-26
      • 2020-12-30
      相关资源
      最近更新 更多