js按條件分類json數組,並合計同組數據(一維轉換為二維)


let _items = response.json()
      // console.log(_items.data)
      let json1 = _items.data
      let json2 = []
      let keyMap = {}
      for (let i = 0; i < json1.length; i++) {
        let json1Elem = json1[i]
        let elemKey = json1Elem.year + '-' + json1Elem.month
        if (elemKey in keyMap) {
          json2[keyMap[elemKey]].value.push(json1Elem)
        } else {
          json2.push({
            'year': json1Elem.year,
            'month': json1Elem.month,
            'value': [json1Elem],
            'goods_number': null,
            'taxless_amount': null,
            'amount': null,
            'tax': null
          })
          keyMap[elemKey] = json2.length - 1
        }
      }
      // console.log(json2)
      for (let i = 0; i < json2.length; i++) {
        json2[i].value.forEach(function (item) {
          json2[i].goods_number = null
          json2[i].taxless_amount = null
          json2[i].amount = null
          json2[i].tax = null
          function getsum (item, arry) {
            json2[i].goods_number += Number(item.goods_number)
            json2[i].taxless_amount += Number(item.taxless_amount)
            json2[i].amount += Number(item.amount)
            json2[i].tax += Number(item.tax)
          }
          json2[i].value.forEach(getsum, json2[i].value)
        })
      }
      console.log(json2)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM