Autofill suggestions from a refined list within a web application

For a while now, I have been diving into the world of JavaScript and Apps Script. However, I've hit a roadblock that has kept me stuck for hours.

My setup involves a Google spreadsheet serving as my data source, containing a list of employees along with the cities they reside in. These employees access a web app through specific Google accounts. What I aim to achieve is an autocomplete feature that filters employees based on their respective city.

The data is structured in a 2-dimensional array - column 1 holds employee names, and column 2 stores their corresponding cities. After retrieving the user's email upon login, I successfully identify the city associated with them from the spreadsheet.

Next, my function scans through the list of employees, generating a single-dimensional array comprising only those individuals located in the specified city.

function getNames() {
  var ss = SpreadsheetApp.openById(id);
  var wsMail = ss.getSheetByName('MAILS');
  var wsAteliers = ss.getSheetByName('ATELIERS')
  var dataPerso = wsAteliers.getDataRange().getValues();
  var data = wsMail.getDataRange().getValues();
  var people = [];
  var email = Session.getActiveUser().getEmail();

  // TO FIND THE CITY, NO PROBLEMS
  for (var i = 0; i < data.length; i++) {
    if (data[i][0] == email) {
      var atelier = wsMail.getRange('B' + (i + 1)).getValue();
    }
  }

  //RETURNS ARRAY OF NAMES FROM CORRESPONDING CITY
  for (var i = 0; i < dataPerso.length; i++) {
    if (dataPerso[i][1] == atelier) {
      people.push(dataPerso[i][0]);
    }
  }
  return people;
}

The resulting 'people' array looks like this:

https://i.sstatic.net/ovm3R.png

However, when I attempt to convert this array into an object suitable for materialize autocomplete using the following snippet:

var options = {};

dataPerso.forEach(function(v){
  options[v[0]] = null;
});

I end up with this unexpected outcome:

https://i.sstatic.net/GWLPd.png

The ideal result should resemble something like this:

{name1=null, name2=null etc...}

Feeling a bit lost here. Any guidance or pointers would be greatly appreciated.

Thank you,

Answer №1

It seems like there may be an issue with your options value, as using options[v[0]] instead of options[v] could result in accessing single letters rather than the full string.

Alternatively, you can consider utilizing the fromEntries method:

function myFunction() {
  const array = ["Ben", "John"];
  const obj = Object.fromEntries(
    array.map(name => [name, null])
  )
  Logger.log(obj);
}

Output:

https://i.sstatic.net/d72PC.png

References:

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

The form data is being passed as null to HttpContext.Current.Request

My file upload module is working well with Postman without any content type. However, in the code, the file count always shows as 0 in the backend API. If anyone has any insights into what I might be doing wrong, please help me out. Thank you. Below is my ...

The get method is functional, however, the post method is not working as expected in Zap

I'm currently using zapworks studio to create an AR experience. This involves using Z.ajax for ajax calls, including GET and POST requests. For hosting couchdb, I've opted for smileupps due to their free hosting service. The CORS configuration is ...

Is it possible to alter the canvas origin when using an Orthographic camera with a CSS3D

When transitioning the camera from perspective to orthographic, I noticed that the camera's position also shifts so that the coordinates 0,0,0 are situated in the top left corner. Is this expected behavior? Check out this Example for reference. Ortho ...

div maintain aspect ratio while scaling

My current layout is structured like this: HTML <div id="container"> <div id="zoomBox"> <div class="box"></div> <div class="box"></div> <div class= ...

Tips for utilizing data attribute in jQuery programming

How can I modify my jQuery code to select the data attribute "data-price" instead of the value attribute? Sample HTML code: <span id="priceToSwap3"">$238</span> <select id="trapsize"> <option data-price="238">item1</option> ...

The error mentioned above was encountered within the <App> element: specifically in the App component

I recently started the Knowthen Go/React tutorial and am encountering some difficulties with React. When I attempt to launch my application, I encounter this error and I can't seem to pinpoint the cause. Here is the link to my GitHub repository where ...

Simplifying class selection in event delegation with jQuery by using serial numbers

Creating a web quiz involves dynamically generating each question and option element based on an array. Here is the script I am using: function displayQuestions(){ for(let i = 0; i < QuesPartA.length; i++){ $(".questionBox").append ...

Exploring the Fundamentals of Arrays and For Loops in Javascript

Currently learning javascript on my own, with a background in C++. Stumbled upon this code snippet while studying and found the for loop structure quite peculiar: <html> <head> <script type="text/javascript> <!-- function ReadCookie( ...

Header Overflow Error Encountered in Node.js GET Request

While attempting to programmatically submit a form through Google forms using a GET request, I encountered the error message Parse Error: Header overflow. The debug code output is as follows: REQUEST { uri: 'https://docs.google.com/forms/d/e/9dSLQ ...

What is the best way to imitate a PubNub event in a Jest test that was added using pubnub.addListener?

Currently, I am working on a package that utilizes PubNub. My goal is to write jest tests for all the package files, but I have encountered an issue. Specifically, I am struggling to figure out how to cover events within the listener. // add listener ...

Determine the absolute path with respect to a different reference path, rather than the current working directory

One of the challenges I'm facing with my Node.js module is how to easily allow developers to edit the location of the dependencies relative to the module file itself. The issue arises because the current working directory, accessed through `process.cw ...

Forwarding images from a server to a client using socket.io and node.js

I am encountering an issue where I am trying to receive an image via socket.io in node.js and then forward it to a client (browser). However, the image sent through the message to the browser is not being recognized or displayed. Interestingly, if I save ...

ReactJS Error: Cannot find reference to 'require'

I'm currently implementing the DRY concept in React JS by attempting to reuse the same HTML partial across different files. Here is the partial: var AdminMenu = React.createClass({ getInitialState: function() { return {}; }, render: function() ...

Using the same geometric shapes repeatedly leads to occasional texture errors in THREE.JS

As I embark on my journey to create my first card game using THREE.js for Firefox and Chrome, I have encountered a perplexing issue with disappearing textures. The purpose of this post is to gain insights into why this issue occurs and how I can resolve i ...

What is the best way to execute operations on two distinct datasets within a single function using RxJS?

Is there a way to perform operations on two separate data collections within a single function in RxJS, returning an observable instead of void? This function is located within a service and I intend to subscribe to it from my component. I believe some re ...

The function parameter in Angular's ngModelChange behaves differently than $event

How can I pass a different parameter to the $event in the function? <div class='col-sm'> <label class="col-3 col-form-label">Origen</label> <div class="col-4"> <select ...

Is there a way in JavaScript to determine if a textarea contains text that is only one line long?

My aim is to modify the behavior of a textarea based on its content, specifically if it contains more than one line of text. The default setting for a textarea is to have enough height for 2 rows even when empty, which I want to change. I would like to f ...

Delivering information to personalized components using React Bootstrap

I am working with a custom styled checkbox that is part of a mapped data array. {nfcArray && nfcArray.map((item, key) => { return ( <tr class="hover"> <td className="cell_style pl-3 pl-lg-5"> ...

Transitioning the height of a Vue component when switching routes

I've been struggling to implement a transition slide effect on my hero section. The height of the hero is set to 100vh on the homepage and half of that on other pages. Despite trying various methods, I haven't been able to get it working properly ...

Encountering a Mogoose validation error while attempting to write a test involving nested objects

I'm currently developing a small application that utilizes javascript, node.js, mongoDB, and mongoose. Within this application, I have two collections - users and groups. Each group contains an array of users. User Schema: {_id:{type: String, require ...