I have a table array which looks like this:
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}
]
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
newObject = indexByColumnValues(tablearray, ['column1', 'column2']);
should result in an object like
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}
}
}
So
newObject[1][1]['column3'] = 1
newObject[1][2]['column4'] = 4
etc...
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
newObject[tablearray[columnNameArray[0]][tablearray[columnNameArray[1]][tablearray[columnNameArray[2]]...
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]].
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;
}
Any help or hints would be great here. Thanks.
You mention recursion, but you don’t use it in your code. This is a classic situation where recursion is the right tool. Here’s one implementation:
Note that, as @jfriend00 notes, you want the “leaf” of your index to be an array of matching rows, not a single object – it’s just coincidence that in your example you only have one matching row for your given data and set of columns. Usage:
Output:
JsFiddle: http://jsfiddle.net/RRcRM/3/