1

我从服务器获取数据数组,但是在来到 jquery 数据表之后我需要多维数组。有没有办法在 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

不久前,当我遇到类似问题时,我发现了这个美丽的问题。这是一个基于(erm ..从那里撕掉)的解决方案:

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

来自未来的信息 ;) - 现在我们减少了:

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 回答