Autocomplete from a filtered array in web app

Viewed 78

I've been learning JavaScript and Apps Script for a little while now, and I'm stuck on this one part, and have been for the past couple of hours.

So I have a google spreadsheet as my data source, with a list of employees, and the cities they're in. Now they all connect to this web app through specific google accounts, and what I want to do is make an autocomplete list, but with only the people from that specific city.

I have a 2 dimensional array, column 1 has the names, column 2 has the cities they are in. My function first gets the email they log on with, and then filters a list to find the corresponding city which is stored in a variable. This part works fine.

Then my function looks at the list of employees, and creates a 1 dimensional array with only the names form that specific 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;
}

output of people is as follows :

Result of array 'people'

When i try to convert this to an object for the materialize autocomplete, like this :

var options = {};

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

I get this result:

object result

As you can see, not exactly the result I want, it should be more like:

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

I'm honestly lost, could anybody give me some pointers please?

Thanks,

1 Answers

I'm not sure what your options value is but I'm sure your issue is using options[v[0]] instead of options[v] thus resulting into having single letters as you are accessing the first character of the string.

Although I prefer this approach using fromEntries instead:

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

Output:

output

References:

Related