【问题标题】:Sum values of objects in arrays of array数组数组中对象的总和值
【发布时间】:2019-05-24 11:08:49
【问题描述】:

我正在尝试对对象的值求和。我有一组对象数组。

(7) [Array(5), Array(29), Array(32), Array(20), Array(10), Array(1), Array(1)]

需要分别对每个数组对象的“数量”值求和,例如:

1: Array(29)
  0:
    id: "PXvWizOLCPbHCUzHxUoK"
    productName: "someProduct"
    productPrice: "146"
    quantity: 3
  1:
    id: "PXvWizOLCPbHCUzHxUoK"
    productName: "someProduct"
    productPrice: "156"
    quantity: 7 
   etc...

换句话说,需要得到数组[1]、数组[2]中所有对象的“数量”总和...

一些尝试:

1)

let quantityOfProduct = arrayOfArraysOfObjects[0].reduce((acc, current) => {
    return{
        quantity: acc.quantity + current.quantity
    }
})

2)

let result:any = []
arrayOfArraysOfObjects[0].reduce((acc, current) => {
    result.push({[current.id]: acc.quantity +current.quantity})
})

上述尝试得到错误“reduce is not defined”,我也在使用 Typescript。

有什么建议或想法吗?

提前谢谢你。

【问题讨论】:

    标签: javascript arrays typescript object ecmascript-6


    【解决方案1】:

    只需使用mapreduce

    const quantities = arrayOfArraysOfObjects.map(a => a.reduce((acc, { quantity }) => acc + +quantity, 0));
    

    【讨论】:

      【解决方案2】:
      let res = 0;
      arr.forEach((data1,index,arr)=>{
          data1.forEach(({qunt})=>{
              res+=qunt
          })
      })
      console.log(res)
      

      【讨论】:

        【解决方案3】:

        考虑arrayOfArraysOfObjects 是变量的名称。您需要在主数组上使用 map() 并使用 reduce() 获取每个数组的总和

        let res = arrayOfArraysOfObjects.map(x => x.reduce((ac,a) => ac + a.quantity,0));
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-09-25
          • 2021-03-15
          • 2020-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-09-05
          • 1970-01-01
          • 2021-03-11
          相关资源
          最近更新 更多