Create an object that stores the two-dimensional values of rows and columns from a Google Sheet

Hey there! I'm currently working on a project where I need to extract values from the 1st and 2nd rows and store them in an object. Here's my current code:

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 quantityFiltered = quantity[0].filter(item => item);
  var fruitFiltered = 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]
    }
  }

However, I'm not satisfied with this approach and the for loop seems to be stuck. I want to automate this process more to minimize errors in the data.

What I really need is an object structured like this:

{
    "Apple": 23,
    "Banana" 25,
    "Apple": 30,
    "Grapes": "No value",
    "Apple": 31
}

Do you think it's possible to write a code using an approach similar to the following example?

dic = {}

for quantity,fruit in zip(ss.getRange(2,4,2,24).getDisplayValues(), ss.getRange(3,4,3,24).getValues()):
    dic[fruit] = key

This pythonic approach works well, but I need to convert it into JavaScript for app script purposes.

Check out this image of the sheet for reference

Answer №1

After reviewing your Python code, it seems like you are facing difficulties in achieving the following:

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 want to calculate the total for each existing key (fruit), you can use this method:

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)

This equivalent Python translation would look something like:

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'}

You may also need to address how to handle the 'No value' entries as they could potentially introduce errors in this simple implementation.


Just a heads up. Here's one possible approach to dealing with 'No value' entries:

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 ]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am attempting to update the URL of an iframe dynamically, but I am encountering an issue: the Error message stating that an Unsafe value is being

Currently, I am attempting to dynamically alter the src of an iframe using Angular 2. Here is what I have tried: HTML <iframe class="controls" width="580" height="780" src="{{controllerSrc}}" frameborder="0" allowfullscreen></iframe> COMPONE ...

Transform the Nodejs server into a reusable Node module

Can a nodejs API server be transformed into a node module for use in other projects with minimal code modifications? Additional Information: The node js server contains various APIs (get, post, put). If I integrate this server as a node module within anot ...

Angular: Dividing a web page with its individual controller

Exploring Angular Composition An individual new to Angular is eager to implement the concept of "composition," where the main page contains various smaller web page components. Starting off with just a Header section that binds perfectly. <html> &l ...

Switch the displayed image(s) based on the radio button selection made by the user

I need help implementing a feature on my website where users can change an image by selecting radio buttons. For example, there are three options: 1) Fox 2) Cat 3) Dog When the user chooses "Fox," I want an image of a fox to be displayed. If they then sw ...

How can I incorporate Bootstrap 5 into my Storybook setup?

As I work on constructing a storybook, I am exploring the idea of integrating Bootstrap 5 into it. I am wondering if the most effective approach to implement it is by utilizing a preview-head.html file within the .storybook directory. Despite my efforts ...

Developing a NestJs application using mongoose where collection names are dynamically generated

My goal is to dynamically change collection names based on the current year. For instance, from 'products' to 'products2020'. When using NESTJS, I need to import "module.forFeature" with a specific collection name. import { Module } f ...

What is the process for creating a dynamic URL, such as example.com/profile/CroatiaGM?

I am in the process of developing a user control panel, and I have encountered some difficulties with creating a dynamic profile link. For instance, how can I achieve something like example.com/profile/CroatiaGM? Given that my website is primarily coded ...

Angular: Preserve the URL even when encountering a 404 page

Creating a custom 404 page in Angular 4 is something I have recently done, and I am looking for a way to preserve the incorrect URL that was input by the user. To see an example of this behavior, you can visit sites like GitHub. They show a 404 page when a ...

Ways to extract the final digit from a format such as an IP address in JavaScript

Is there a way to retrieve the last digits 192.168.1.180 For instance: From the IP address 192.168.1.180, I would like to extract 180. Thank you in advance ...

Displaying base64 images using Javascript

I am currently attempting to stream the Raspberry Pi camera, and due to security concerns, I've configured my server to tunnel through a secure connection even though both the server and client are on the same local area network (LAN). Unfortunately, ...

Retrieving data from the option page's localStorage using the content script

Currently attempting to develop a straightforward chrome extension, however encountering challenges when trying to access the options.html's local storage from my content script "auto.js". After researching and navigating through Chrome's convol ...

Ways to modify an image URL with JavaScript

<strong class="logo"> <a href="/"> <img width="254" height="236" src="/themes/musika/images/logo.png" alt="logo"></img> <span>text</span> </a> </strong> Looking to dynamically update the image URL using Java ...

Employing jQuery Mobile Cache Manifest with PHP

Exploring the use of jquery mobile cache manifest, I'm curious to know if it's compatible with Php files as well. Appreciate any insights. ...

Multiplying form inputs using JavaScript

I am working on an HTML form that includes arrays: <form method="post" id="formaa" name="form"> <div id="fields"> <div id="divas1" class="row"> <a href="#" id="did1" onClick="d(this);"><img src="d.jpg" /></a& ...

Tips on using javascript to reset an element's inline CSS to its initial default styling?

I have a basic function that alters the default text styling when a checkbox is checked, and restores it to its original state when the checkbox is unchecked. Despite my efforts, the terms.style = ""; line does not reset the style as expected. I am perple ...

Regular expressions - Identifies a text string that doesn't contain <html> tags, including all possible scenarios

Can you identify the issue with this string: This is a bad string.It has <HTML> tags? It contains HTML tags that should not be matched. Can you help me find a good string without any HTML tags (including attributes)? There are many resources availab ...

tips for utilizing namespaced getter filtering within a Vuex module in vueJs

In my custom module named ShopItemCategory, I have a Getter getters: { shopItemsCategories: state => state.ShopItemsCategories.data, }, Inside the component, there is a computed function I defined computed: { shopItemsCategories ...

How can you utilize the Array submission syntax within HTML coding?

I currently have numerous input fields within a form, and some of them are structured like this: <input name="agents[]" type="file" /> Additionally, imagine there is a plus button next to this field as shown below: <img src="plus.jpg" id="some_ ...

How can data be sent to the server in JavaScript/AJAX without including headers?

JavaScript - Is it possible to transfer data to the server backend without using headers? ...

What is the proper way to import Axios in Vue 3 once you have created a new project using the CLI?

When starting a new project, I used the command: vue create hello-world This generated essential files like HelloWorld.vue, app.vue, and main.js. Next, I followed the documentation on Npm vue-axios to install Axios: npm install --save axios vue-axios In ...