Hi I am trying to take values of 1st and 2nd row then add them to a object although I have coded it like below
function getTime(){
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var d = {}
var quantity = ss.getRange(2,4,2,24).getDisplayValues();
var fruit = ss.getRange(3,4,3,24).getValues();
var quantity = quantity[0].filter(item => item);
var fruit = fruit[0].filter(item => item);
for (let i = 0; i < quantity.length; i++) {
for (let j = 0; j < fruit.length; i++){
d[quantity[i]] = fruit[j]
}
}
But I do not like this approach (secondly, this for loop stuck) so I want to make more automated so for less errors in data
what I need is an object like this
{
"Apple": 23,
"Banana" 25,
"Apple": 30,
"Grapes": "No value",
"Apple": 31
}
Is it possible to code it somewhat like below approach
dic = {}
for quantity,fruit in zip(ss.getRange(2,4,2,24).getDisplayValues(), ss.getRange(3,4,3,24).getValues()):
dic[fruit] = key
the above approach is in python but for app script I need converted it into javascript.
Based on your Python code I assume you're struggling to make this:
var d = {};
var fruit = ["Apple", "Banana", "Apple", "Grapes", "Apple"];
var quantity = [23, 25, 30, "No value", 31];
fruit.forEach((f,q) => d[f] = quantity[q]); // <-- the JS magic is here
console.log(d);
Update
If you need to sum all existed keys (fruits) here is the way:
var d = {};
var fruit = ["Apple", "Banana", "Apple", "Grapes", "Apple"];
var quantity = [23, 25, 30, "No value", 31];
fruit.forEach((f,q) => d[f] = d[f] ? d[f] + quantity[q] : quantity[q]);
console.log(d)
Which in direct translation to Python will look about like this:
d = {}
fruits = ["Apple", "Banana", "Apple", "Grapes", "Apple"]
quantity = [23, 25, 30, "No value", 31]
for f,q in zip(fruits,quantity):
try: d[f] += q
except: d[f] = q
print(d) # output: {'Apple': 84, 'Banana': 25, 'Grapes': 'No value'}
And probably you need to handle somehow the 'No value' values. They can be a source of errors in this simply implementation.
Just in case. Here's one of the ways to handle 'No value' values:
var s = ['No value', 'No value25', 25, '10', ''];
const get_num = s => s = (s == 'No value') ? s : +s.toString().replace(/\D+/g,'');
console.log(s.map(x => get_num(x))); // output: [ 'No value', 25, 25, 10, 0 ]