1

サーバーからデータの配列を取得していますが、jquery datatable にアクセスした後、多次元配列が必要です。データテーブルに渡す前に jquery 自体でそれを作成する方法はありますか?

私の入力形式は次のとおりです。

["computer","program","laptop","monitor","mouse","keybord","cpu","harddrive"......]

予想される形式:

[["computer","program","laptop","monitor"],["mouse","keybord","cpu","harddrive"],[....],[....]........]

データ形式を解析する方法はありますか?

4

3 に答える 3

2

while配列を変換するには、単純なループ以上のものは必要ありません。

// This is the original data we get from the server
var input  = ["computer","program","laptop","monitor","mouse","keybord","cpu","harddrive"];
// Make a copy of the input, so we don't destroy it
var data = input.slice(0);
// This is our output array
var output = [], group;
// A while loop will transform the plain array into a multidimensional array
while (data.length > 0) {
    // Take the first four items
    group = data.splice(0, 4);
    // Make sure the group contains 4 items, otherwise pad with empty string
    while (group.length < 4) {
        group.push("");
    } 
    // Push group into the output array
    output.push(group);
}
// output = [["computer","program","laptop","monitor"],["mouse","keybord","cpu","harddrive"]]

更新: 入力のコピーを作成するため、Beetroot-Beetroot のコメントは無効になりました。

于 2013-06-23T15:42:43.050 に答える
0

私は似たような問題を抱えていたときに、この美しい質問を見つけました。これは、それに基づいたソリューションです(ええと..そこから切り取ったものです):

var a = ["computer", "program", "laptop", "monitor", "mouse", "keybord", "cpu", "harddrive", "tablet"],
    n = a.length / 4,
    len = a.length,
    out = [],
    i = 0;
while (i < len) {
    var size = Math.ceil((len - i) / n--);
    out.push(a.slice(i, i + size));
    i += size;
}

alert(JSON.stringify(out));
于 2013-06-23T16:07:44.350 に答える
0

未来からのメッセージ ;) - これでreduce:

function groupArray(array, groupSize) {
  return array.reduce((a, b, i) => {
    if (!i || !(i % groupSize)) a.push([])
    a.slice(-1).pop().push(b)
    return a
  }, [])
}
console.log(groupArray(input, 4))
//   [ 
//     [ 'computer', 'program', 'laptop', 'monitor' ],
//     [ 'mouse', 'keybord', 'cpu', 'harddrive' ] 
//   ]
于 2016-04-27T21:27:44.603 に答える