在筛选这个数组之后,我尝试在数组中创建公式,我的数组有时不给我价格,有时也不给我总价:如果数组中的价格为0.0,我想将它更改为TotalPrice/Qty,就像第一个数组600/20=30,价格是30。在第二个数组中,这是我的代码: TotalPrice是0.0,do Qty_Price=TotalPrice : 10_20=200,thee是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: 就像这张照片:在这里输入图像描述
发布于 2021-08-04 13:29:14
可能是这样的:
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);
}输出:

https://stackoverflow.com/questions/68651168
复制相似问题