美文网首页
两个数组json 各项相加成新数组

两个数组json 各项相加成新数组

作者: 糖醋里脊120625 | 来源:发表于2024-01-15 10:22 被阅读0次
    1.简单数组
    let sourceData = [
            [1, 2,3,5,56,77,8,89],
            [1, 2,3,5,56,77,8,89],
            [1, 2,3,5,56,77,8,89],
        ]
        function getTotalByArray (sourceData) {
            let col = sourceData[0].length
            let row = sourceData.length
            console.log(col)
            console.log(row)
            let result = []
            
            for(var i = 0; i < col; i++){
                var temp = []
                for (var j = 0; j < row; j++) {
                    temp.push(sourceData[j][i])
                }
                console.log(temp); // 代码块一
                let tatal = temp.reduce((total, item) => {
                    return total+item
                }, 0)
                result.push(tatal)
            }
            console.log(result); // 代码块二
        }
     代码块一结果
    [ 1, 1, 1 ]
    [ 2, 2, 2 ]
    [ 3, 3, 3 ]
    [ 5, 5, 5 ]
    [ 56, 56, 56 ]
    [ 77, 77, 77 ]
    [ 8, 8, 8 ]
    [ 89, 89, 89 ]
    
    result结果为
    [
        3,   6,  9,  15,  168, 231, 24, 267
    ]
    
    2.复杂json的运算
    getTotalByArray (sourceData) {
          const col = sourceData[0].childArrayList.length
          const row = sourceData.length
          const result = []
          for (var i = 0; i < col; i++) {
            var temp = []
            for (var j = 0; j < row; j++) {
              temp.push(sourceData[j].childArrayList[i])
            }
            //  console.log(temp); // 代码块一
            const tatalorder = temp.reduce((total, item) => {
              return total + item.itemTimeCountVal.orderQuantity
            }, 0)
            const tatalreg = temp.reduce((total, item) => {
              return total + item.itemTimeCountVal.regQuantity
            }, 0)
            result.push({
              monthOrDayVal: i,
              itemTimeCountVal: {
                orderQuantity: tatalorder,
                regQuantity: tatalreg
    
              }
    
            })
          }
          return result
        }
    

    相关文章

      网友评论

          本文标题:两个数组json 各项相加成新数组

          本文链接:https://www.haomeiwen.com/subject/wtqhodtx.html