Search code examples
javascriptjqueryjsonjqgrid

How to dynamically bind and rows and column in JqGrid?


I want to form a JqGrid using the below JSON and the below JSON may change frequently.

{
  "rowvalue": [
    {
        "company": "test",
        "price": 98,
        "Change": 8,
        "perchange": 8,
        "LastUpdated": "2",
        "companyid": 2
    },
    {
        "company": "test123",
        "price": 1,
        "Change": 1,
        "perchange": 1,
        "LastUpdated": "1",
        "companyid": 3
    },
    {
        "company": "abc",
        "price": 1234,
        "Change": 123,
        "perchange": 1,
        "LastUpdated": "1",
        "companyid": 1
    }
  ]
}

Here is my code:

$("#table_div" + chartId).empty().jqGrid({
  datatype: 'json',
  data: data,
  jsonReader: {
    repeatitems: false,
  },
  colNames: getColNames(data),
  colModel: getColModels(data),
  rowNum: 50,
  rowList: [50, 100, 150, 200],
  autowidth: true,
  height: '100%',
  shrinkToFit: false,
  gridview: true,
  autoencode: true,
  sortorder: "asc",
  viewrecords: true,
  ignoreCase: true,
  hoverrows: true,
  caption: title
});

function getColNames(data) {
  var keys = [];

  for (var i = 0; i < data.rowValue.length; i++) {
    for (var key in data.rowValue[i]) {
      if (data.rowValue[i].hasOwnProperty(key)) {
        keys.push(key);
      }
    }

    break;
  }
  
  return keys;
}

function getColModels(data) {
  var colNames = getColNames(data);
  var colModelsArray = [];

  for (var i = 0; i < data.rowValue.length; i++) {
    var str;

    if (i === 0) {
      str = {
        name: colNames[i],
        index: colNames[i],
        key: true,
        editable: true
      };
    } else {
      str = {
        name: colNames[i],
        index: colNames[i],
        editable: true
      };
    }

    colModelsArray.push(str);
  }

  console.log(colModelsArray)

  return colModelsArray;
}

I am succesfull in getting columns any how. But I have a problem in getting colmodels.

I am newbie in JavaScript. Any help would be appreciated.

Note: rowValue will change dynamically

Thanks in advance!


Solution

  • ---- ColName ----- var colName = Object.keys(data["rowvalue"][0]);

    ---- ColModel ----
    var colModel = [];
    for(var i=0; i<colName.length; i++) {
        var tempColModel = {};
        tempColModel["name"] = colName[i];
        tempColModel["id"] = colName[i];
        tempColModel["width"] = 90;
        colModel.push(tempColModel);
    }
    

    Please add rest of the properties in the ColModel as per your condition.