如何在JavaScript中将数组嵌套在另一个数组中?

时间:2012-12-04 20:14:39

标签: javascript jquery arrays

我需要将我在JSON中创建的数组嵌套在另一个数组中,以便为jQuery Datatables library.正确格式化

这是我目前的代码:

$.ajax({
    url: uMtbls,
    dataType: 'json',
    success: function(jMtbl) {
        $.each(jMtbl, function(i, item) {
            mAll = jMtbl[i];
            mOwn = jMtbl[i].OrigOwner;
            mPub = jMtbl[i].PublicationTblNm;
            mTbl = jMtbl[i].TableId;
            mMig = jMtbl[i].MigrationFreq;
            mGTYPE = jMtbl[i].GTYPE;
            exec();

        });

        oTable = $('#dtManaged').dataTable({
            "bStateSave": true,
            "bProcessing": true,
            "bServerSide": true,
            "aaData": jReform,
            "aoColumns": [{
                "sName": mOwn,
                "sTitle": "Original Owner",
                "sWidth": "10%"
            }, {
                "sName": mPub,
                "sTitle": "Table Name"
            }, {
                "sName": mTbl,
                "sTitle": "ID"
            }, {
                "sName": mMig,
                "sTitle": "Migration Frequency"
            }, {
                "sName": mGTYPE,
                "sTitle": "Oracle Gtype"
            }],
            "sPaginationType": "full_numbers",
            "iDisplayLength": 25,
            "aLengthMenu": [
                [25, 50, 100, -1],
                [25, 50, 100, "All"]
            ]
        });
    }
});

function exec() {
    jBld = mOwn + "," + mPub + "," + mTbl + "," + mMig + "," + mGTYPE;
    //console.debug("[" + mOwn + "," + mTbl + "]");
    jReform = jBld.split(",");
    console.debug(jReform);
}​

输出看起来像这样(在console.debug中捕获):

["text","text","text","text","text"]
["text","text","text","text","text"]

样本应该是:

{ "aaData": [
  [ 10126, 10002253, 415 ]
]}

1 个答案:

答案 0 :(得分:1)

使用Array.push。并且使用var语句,您正在创建一个全局变量。

var aaData = [];
$.each(jMtbl, function (i, item) {
  aaData.push([
    item.OrigOwner,
    item.PublicationTblNm,
    item.TableId,
    item.MigrationFreq,
    item.GTYPE
  ]);
});

oTable = $('#dtManaged').dataTable({
  ...
  "aaData": aaData,
  ...
});

(注意:这些链接不仅仅用于展示,请仔细阅读。)