【问题标题】:Get the reduce of the array within array Javascript获取数组Javascript中数组的reduce
【发布时间】:2019-03-30 01:35:41
【问题描述】:

我试图在sku 数组中获取我的packings 数组的总数。我有 mapped 和 reduced 数组,但它给了我一个 undefined 输出。

sku: [
  {
    id:1,
    value:0,
    packings: [
      {
        id: 1,
        cost: 0,
        code:'',
        pieces: 0,
        size:0,
        total:0
       },
    ],
  },
],

这是我的代码:

let result = this.sku
    .map ( (obj,index) => {
        parseFloat(obj.packings.total);
        console.log(obj.packings.total)
    })
    .reduce( (total,current) => {
        total+current;
    }) 

return this.fixFourDecimal(result);

注意skupackings是动态的,用户可以在一个sku内加/乘packings,也可以加多个sku

【问题讨论】:

    标签: javascript arrays function ecmascript-6


    【解决方案1】:

    如果您在箭头函数 => 内使用花括号 {},它不会让您隐式返回 - 您必须使用 return 关键字或重构您的函数:

    let result = this.sku
      .map((obj, index) => {
        console.log(obj.packings.total);
        return parseFloat(obj.packings.total);
      })
      .reduce((total, current) => total + current);
    

    【讨论】:

      猜你喜欢
      • 2018-12-07
      • 2017-05-05
      • 2020-04-24
      • 2021-07-08
      • 2015-05-19
      • 1970-01-01
      • 1970-01-01
      • 2021-06-02
      • 2013-07-12
      相关资源
      最近更新 更多