title: JavaScript: Indexing an object by column values
body: <p>I have a table array which looks like this:</p>
  
  <pre><code>tablearray =
  [
      {'column1': 1, 'column2': 1, 'column3': 1, 'column4': 2},
      {'column1': 1, 'column2': 2, 'column3': 3, 'column4': 4},
      {'column1': 2, 'column2': 0, 'column3': 4, 'column4': 6}
  ]
  </code></pre>
  
  <p>I'm trying to make a function which takes the table array and an array of column names and makes a new object indexed by the column values.  So</p>
  
  <pre><code>newObject = indexByColumnValues(tablearray, ['column1', 'column2']);
  </code></pre>
  
  <p>should result in an object like</p>
  
  <pre><code>newObject =
  {
      1:
          {
              1: {'column1': 1, 'column2': 1, 'column3': 1, 'column4': 2},
              2: {'column1': 1, 'column2': 2, 'column3': 3, 'column4': 4}
          }
      2:
          {
              0: {'column1': 2, 'column2': 0, 'column3': 4, 'column4': 6}
          }
  }
  </code></pre>
  
  <p>So</p>
  
  <pre><code>newObject[1][1]['column3'] = 1
  newObject[1][2]['column4'] = 4
  etc...
  </code></pre>
  
  <p>If the number of columns in the column name array (['column1', 'column2'] above) is known, the solution is not hard.  But if I allow for any number of column names in this array, it becomes more difficult as there is indefinite recursion</p>
  
  <pre><code>newObject[tablearray[columnNameArray[0]][tablearray[columnNameArray[1]][tablearray[columnNameArray[2]]...
  </code></pre>
  
  <p>Here is one attempt.  I tried to use a pointer to point to the dimensional depth of the newObject array.  First, pointer = newObject.  Then pointer = newObject[...[0]].  Then point = newObject[...[0]][...[1]].  And so on.  This builds the object properly but then I do not have a way to assign a value to newObject[...[0]]...[...[k]].</p>
  
  <pre><code>function indexByColumnValues(object, columnNameArray)
  {
      var newObject = {};
  
      for(i in object)
      {
          var index=[];
  
          for(j in columnNameArray)
          {
              index.push(object[i][columnNameArray[j]]);
          }
  
          var pointer = newObject;
  
          for(j in index)
          {
              if(pointer[index[j]] == undefined)
              {
                  pointer[index[j]] = {};
              }
  
              pointer = pointer[index[j]];
          }
  
          //now pointer points to newObject[index[0]][index[1]]...[index[k]]
          //but I need to set newObject[...] above to be object[i].  How?
          //pointer = object[i]; //won't work
      }
  
      return newObject;
  }
  </code></pre>
  
  <p>Any help or hints would be great here.  Thanks.</p>