が、私はこのようになり、テーブルの列を持っている値:私はテーブルの列と列名の配列を受け取り、作る機能を作成しようとしているはJavaScript:列でオブジェクトを索引付けすることは
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}
]
列値によって索引付けされる新しいオブジェクト。そう
newObject = indexByColumnValues(tablearray, ['column1', 'column2']);
そこで
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}
}
}
newObject[1][1]['column3'] = 1
newObject[1][2]['column4'] = 4
etc...
ようにオブジェクトをもたらすべきである場合、列名配列内の列の数(上記[ 'COLUMN1'、 'COLUMN2'] )が知られている場合、その解決策は難しくありません。私はこの配列内の列名の任意の数を可能なら、それはここに1つの試みである不定再帰
newObject[tablearray[columnNameArray[0]][tablearray[columnNameArray[1]][tablearray[columnNameArray[2]]...
があるように、より困難になります。私はポインタを使ってnewObject配列の次元の深さを指し示そうとしました。まず、pointer = newObjectです。次に、ポインタ= newObject [... [0]]。次に、point = newObject [... [0]] [... [1]]。等々。これはオブジェクトを適切に構築しますが、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;
}
ここで役立つヘルプやヒントがあります。ありがとう。
私はあなたがライブラリを使用するか(非常に便利です)独自のコードから学びたいしたいかどうかわかりませんunderscore.jsには '_.groupBy'があります。 – pimvdb
結果の内部オブジェクトは、一致する列の値が1つの各オブジェクトを保持する配列であるべきではありませんか? – jfriend00
@ jfriend00私の目的として、私が使用することを期待している列の値の組み合わせが一意であるため、内部の配列は不要です。 –