转换JavaScript数组

时间:2013-06-23 15:36:13

标签: javascript

我从服务器获取数据数组,但是来到jquery数据表之后我需要multidimention数组。是否有任何方法可以在jquery中将它传递给datatables?

我的输入格式为:

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

预期格式:

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

有没有解析数据格式的方法?

3 个答案:

答案 0 :(得分: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的评论不再有效,因为我们创建了一个输入副本。

答案 1 :(得分:0)

在我遇到类似问题的时候,我发现了beautiful question。这是一个基于(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));

答案 2 :(得分: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' ] 
//   ]