操纵数组以获取对象集合

时间:2019-06-18 14:55:01

标签: javascript arrays sorting google-apps-script

我正在尝试在数组上进行操作,并一直坚持实际操作方法。 我已经使用App Script在Google表格中创建了一个日历,然后获取了在给定时间范围内发生的所有事件(即单元格的笔记),并希望对数据进行划分以获得该人的姓名以及该人将负责的所有事件。

function getEvents(){ 
  var numRows = range.getNumRows(); 
  var numCols = range.getNumColumns(); 
  var trainingTable = [] 
  var note, cell 
  for (var i = 3; i <= numRows; i++) { 
    for (var j = 1; j <= numCols; j++) { 
      cell = range.getCell(i,j) 
      note = cell.getNote(); 

      //if the cell has a note push it into table
      if(note){ 
        trainingTable.push(note.split('\n')) 
        /* output 
        [ 
        [Ringo Starr, event 3, may 25], 
        [Paul McCartney, event 2, june 15], 
        [Ringo Starr, event X, february 2], 
        [George Harrison, event Y, may 25], 
        [Paul McCartney, event Z, june 15] 
        ] 
        up to 20 different people
        */
      } 
    } 
  } 
  for( var i in trainingTable ){
    // yes, what goes here?
    //how to distinct names and attach events to them
  }
}

我想为每个人创建一个配置文件对象,并将事件附加为这些对象的属性,但是该怎么做呢?

//编辑 如您所见,Ringo Starr有两个不同的事件,所以理想的配置文件是:var person1 = {name: Ringo Starr, e1: [event 3, may 25] , e2: [event X, february 2] }

谢谢您的回答。 最好。

1 个答案:

答案 0 :(得分:0)

这将在配置文件数组中搜索艺术家名称。如果找不到它(-1),那么它将创建一个新的p对象并将其添加到配置文件数组中。如果确实找到了艺术家的名字,它只会将新的事件和日期添加到艺术家个人资料中的相应数组中。

        trainingTable = [ 
        ["Ringo Starr", "event 3", "may 25"], 
        ["Paul McCartney", "event 2", "june 15"], 
        ["Ringo Starr", "event X", "february 2"], 
        ["George Harrison", "event Y", "may 25"], 
        ["Paul McCartney", "event Z", "june 15"] 
        ] ;

        var profile = [];
        for(x=0; x<trainingTable.length; x++) {
            t = trainingTable[x];
            var nameIndex = profile.findIndex(n => n.name === trainingTable[x][0]);
            if(nameIndex === -1) { 
                p = {
                    "name" : trainingTable[x][0],
                    "event" : [trainingTable[x][1]],
                    "date" : [trainingTable[x][2]]
                }
                profile.push(p);
            } else {
                profile[nameIndex].event.push(trainingTable[x][1]);
                profile[nameIndex].date.push(trainingTable[x][2]);  
            }
        }

        var person1 = profile[0];
        console.log(person1);