js 使用 :解释数据结构、分组汇总

一、 JSON.parse 妙用

用如下语句打印:

console.info(result);
      console.info(result.data);
      console.info(JSON.parse(result.data));
      console.info(JSON.parse(result.data).data.PriceSheetId);
      console.info(result.data.Data);

打印结果:第三个打印显示的形式才可以用  点属性的方式出来。 第一个打印里面有\",这样是不可以直接 点出来的。

 二、分组汇总:

 const groupBy  = (arr, groupKey, getValue) => {
        return arr.reduce((acc, item) => {
          const key = item[groupKey];
          if (!acc[key]) {
            acc[key] = getValue(item);
          }
          return acc;
        }, {});
      };

      const groupItems = groupBy(rowDataTmp, 'DepotOutListId',item=>item.ExQty);
      sumOutQty = Object.values(groupItems).reduce((acc, value) => acc + value, 0); 

 只能汇总一列数值

const groupByAndSum = (array, groupBy, sumBy) => {
              return array.reduce((acc, item) => {
                const key = item[groupBy];
                if (!acc[key]) {
                  acc[key] = { [groupBy]: key, total: 0 };
                }
                acc[key].total += item[sumBy];
                return acc;
              }, {});
            };            
            console.info(result.rowsGoods);
            const groupedSum = groupByAndSum(result.rowsGoods, 'Warehouse', 'LargePackage');
View Code

分类汇总。好用:

// 按 ProjectCode 分组汇总
        const groupedData = rows.reduce((acc, item) => {
          const key = `${item.ProjectCode}|${item.Customers}`;
         
          if (!acc[key]) {
            acc[key] = {
              ProjectCode: item.ProjectCode,
              Customers: item.Customers,
              items: []
            };
          }
          
          acc[key].items.push(item);
          return acc;
        }, {});
        
        // 获取分组结果数组
        const groupArray = Object.values(groupedData);
        
        // 获取组数和处理逻辑
        const groupCount = groupArray.length;
        
        if (groupCount === 1) {
          // 只有一组时,取出该组的 ProjectCode 和 Customers
          const singleGroup = groupArray[0];  
          // console.log('ProjectCode:', singleGroup.ProjectCode);
          // console.log('Customers:', singleGroup.Customers);   
          this.$refs.gridFooter.open("账单信息选择","开票公司","","month",true,'in',singleGroup.ProjectCode,singleGroup.Customers);
        } 
        else 
        {
          return this.$message.error("存在【多个项目】或【多个委托方】不能生成账单!");
        }
View Code
posted @ 2024-03-08 18:09  丁焕轩  阅读(77)  评论(0)    收藏  举报