动态访问没有键的json对象

时间:2015-12-05 20:14:52

标签: jquery

我正在编写一些代码来生成数据网格形式的json数据。我知道有多个免费库可用于执行相同操作。 下面是我的一段代码

  var columnDefs=[
    {title:"Sr.No",fieldName:"srno",dataType:"int",isHidden:true},
    {title:"Model No.",fieldName:"modelId",dataType:"int"},
    {title:"Name",fieldName:"name",dataType:"string"},
    {title:"Brand",fieldName:"brandName",dataType:"string"},
    {title:"Price",fieldName:"Price",dataType:"double"},
];
var rowData=[
    {srno:"P1",modelId:"1",name:"Moto G3",brandName:"Motorola",price:"13000"},
    {srno:"P2",modelId:"2",name:"Asus ZenFone 2",brandName:"Asus",price:"13000"},
    {srno:"P3",modelId:"3",name:"Lenovo K3 Note",brandName:"Lenovo",price:"9900"},
    {srno:"P4",modelId:"4",name:"Moto E2 4g",brandName:"Motorola",price:"6999"},
    {srno:"P5",modelId:"5",name:"Nexus 5x",brandName:"LG",price:"24000"},
    {srno:"P6",modelId:"6",name:"Apple iPhone 5s",brandName:"Apple",price:"56000"},
];
var gridOptions={
    title:"Demo Grid",
    columnDefs:columnDefs,
    rowData:rowData
};

document.addEventListener("DOMContentLoaded", function() {
    debugger;
    createDataGrid('#myGrid', gridOptions);
});



//library
function createDataGrid(div,gridDef){
    var gridTitle=gridDef.title
    var titleDiv='<div>'+gridTitle+'</div>';
    $(div).append(titleDiv);
    var table="<table id='tab1' border='1'></table>";
    $(div).append(table);
    $("#tab1").append("<tr id='tbheadres'></tr>");
    //render column headers
    $.each(gridDef.columnDefs,function(index,value){
        var columnName = gridDef.columnDefs[index].title;
        var columnHeader="<th>"+columnName+"</th>"
        $("#tbheadres").append(columnHeader);
    });

    $.each(gridDef.rowData,function(i1,val1){
        var rowId="row_"+i1;
        $("#tab1").append("<tr id="+rowId+"></tr>");
        $.each(gridDef.columnDefs,function(index,value){
            var field=gridDef.columnDefs[index].fieldName;
            var c1=gridDef.rowData[i1].field;
            var col="<td>"+c1+"</td>";
            $("#"+rowId).append(col);
        });
    });

}

在处理嵌套的$ .each后,它只给每行中的每一列提供“undefined”。我猜行有些问题:

var field=gridDef.columnDefs[index].fieldName;
            var c1=gridDef.rowData[i1].field;

我做错了什么?提前谢谢。

1 个答案:

答案 0 :(得分:0)

更改此行代码:

var c1=gridDef.rowData[i1].field;

var c1=gridDef.rowData[i1][field];