Skip to content
Advertisement

Var not being used in object.var

function myFunction() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('data');
  var data = sheet.getDataRange().getValues();
  var range = sheet.getRange("A1:L" + data.length);
  range.sort(1);
  const people = {};
  for(var i = 0; i < data.length; i++) {
    var name = data[i][0] + data[i][1];
    console.log(i);
    if (!people.name) {people.name = {rows: [i]};} else {people.name.rows.push(i)}

  }
  Logger.log(people);
}

What should I be doing differently? At the end, it logs {name={rows=[0.0, 1.0, 2.0, ...]}} instead of having an object for each name…?

In the sheet there’s just a first name and last name on columns A and B, for around 80 rows.

Advertisement

Answer

Use the bracket syntax if you want to use dynamic names for properties: https://riptutorial.com/javascript/example/2321/dynamic—variable-property-names

In your case:

function myFunction() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('data');
  var data = sheet.getDataRange().getValues();
  var range = sheet.getRange("A1:L" + data.length);
  range.sort(1);
  const people = {};
  for(var i = 0; i < data.length; i++) {
    var name = data[i][0] + data[i][1];
    console.log(i);
    if (!people[name]) {people[name] = {rows: [i]};} else {people[name].rows.push(i)}

  }
  Logger.log(people);
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement