【问题标题】:Create Formula inside array after filter app script google sheet过滤应用程序脚本谷歌表后在数组内创建公式
【发布时间】:2021-10-09 13:16:05
【问题描述】:

我尝试在过滤此数组后在数组内创建公式,我的数组有时不给我价格,有时不给我总价: 我需要如果数组中的价格为 0.0 我想将其更改为 TotalPrice/Qty 就像第一个数组 600/20=30 一样,价格是 30。在第二个数组中 这是我的代码: TotalPrice is 0.0 do QtyPrice=TotalPrice : 1020=200 , 你 TotalPrice 是 200 .

我需要这样的输出:

[{Qty:20, Price:30, TotalPrice:600}, {Qty:10, Price:20, TotalPrice:200}, 
     {Qty:5, Price:100, TotalPrice:500}]

然后我用这段代码把它放在纸上:

sh.getRange(5,5,oA.length, oA[0].length).setValues(oA);

谢谢。

function arrayFormula() {
   const data = '[{"Qty":"20", "Price":"0.0", "TotalPrice":"600"}, {"Qty":"10", "Price":"20", 
     "TotalPrice":"0.0"}, {"Qty":"5", "Price":"100", "TotalPrice":"500"}]';
   
   Logger.log("Array: "+ data);
   const obj = JSON.parse(data);
   const ss = SpreadsheetApp.getActive();

   const oA = obj.map(obj => [obj.Qty, obj.Price,obj.TotalPrice]);

   // put array return to sheet
   //sh.getRange(5,5,oA.length, oA[0].length).setValues(oA);


  var filtered = oA.filter(function (el) {
     if (el[1]!=0) {
       return obj.Total/obj.Qty; 
     } else {
       return false 
     }
  });

 console.log("Array After Filter: " + filtered);

 }

回我:

1:16:27 PM  Info    Array: [{"Qty":"20", "Price":"0.0", "Total":"600"}, {"Qty":"10", 
                           "Price":"20", "Total":"0.0"}, {"Qty":"5", "Price":"100", 
                           "Total":"500"}]
1:16:27 PM  Info    Array After Filter: 

喜欢这张照片: enter image description here

【问题讨论】:

    标签: google-apps-script google-sheets binance binance-api-client


    【解决方案1】:

    大概是这样的:

    function main() {
      const data = `[
        {"Qty":"20", "Price":"0.0", "TotalPrice":"600"}, 
        {"Qty":"10", "Price":"20", "TotalPrice":"0.0"}, 
        {"Qty":"5", "Price":"100", "TotalPrice":"500"}
      ]`;
      const obj = JSON.parse(data);
    
      const calc_price = obj => 
        obj.Price == 0 ? obj.TotalPrice / obj.Qty : obj.Price;
    
      const calc_total_price = obj => 
        obj.TotalPrice == 0 ? obj.Price * obj.Qty : obj.TotalPrice;
    
      const oA = obj.map(o => [o.Qty, calc_price(o), calc_total_price(o)]);
    
      const ss = SpreadsheetApp.getActive();
      const sh = ss.getActiveSheet();
      sh.getRange(5,5,oA.length,oA[0].length).setValues(oA);
    }
    

    输出:

    【讨论】:

    • 你给我来自最后一个数组 {"Qty":"5", "Price":"100", "TotalPrice":"500"} 的数字,我需要像 [{Qty:20, Price:30, TotalPrice:600}, {Qty:10, Price:20, TotalPrice:200}, {Qty:5, Price:100, TotalPrice:500}] 这样的输出,然后我用这个代码 sh.getRange(5,5,oA.length, oA[0].length).setValues(oA); 把它放在工作表上。这就是我需要的,谢谢你的回复
    • 好的。我已经更新(实际上改变了)我的答案。
    猜你喜欢
    • 1970-01-01
    • 2021-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多