如何在SlickGrid中将列映射到复杂对象

时间:2014-02-17 12:18:13

标签: slickgrid

var data = [{"Id":40072,"Id2":40071,"SmDetails":{"Id1":40071,"Id2":40072}}]

我想在列中显示SmDetails.Id1。这怎么可能?我试过了:

var columns = [{name:'Personnel',field:SmDetails.id1,id:'detailId'}];

请帮帮我  请帮帮我

**My latest code**
         var data = [{"Id":40072,"Id2":40071,"allocationDetails":{"Id1":40071,"allocationDetails":{"accommodationId":4007}}}]
    var grid;
                var columns = [                                        {name:"Personnel",field:"allocationDetails",fieldIdx:'accommodationId', id:"accommodationId"}];
                var options = {
                     enableCellNavigation: true,
                    enableColumnReorder: false,
                     dataItemColumnValueExtractor:
                                                                function getValue(item, column) { 
                        var values = item[column.field];                             
                      if (column.fieldIdx !== undefined) {
                return values && values[column.fieldIdx];
                } else {
                return values;
                }}};
                var gridData=$scope.Vo;//This return as json format                         
                grid = new Slick.Grid("#testGrid",gridData, columns);
    This is the code tried recently.

3 个答案:

答案 0 :(得分:0)

您需要提供一个custom value extractor来告诉网格如何阅读您的对象。

var options = {
  enableCellNavigation: true,
  enableColumnReorder: false,
  dataItemColumnValueExtractor:
  // Get the item column value using a custom 'fieldIdx' column param
  function getValue(item, column) { 
    var values = item[column.field];
    if (column.fieldIdx !== undefined) {
        return values && values[column.fieldIdx];
    } else {
        return values;
    }
  }
};

列定义如下:

{
  id: "field1",
  name: "Id1",
  field: "SmDetails",
  fieldIdx: 'Id1'
}, {
  id: "field2",
  name: "Id2",
  field: "SmDetails",
  fieldIdx: 'Id2'
} //... etc

查看this fiddle了解工作示例。

答案 1 :(得分:0)

尝试将data转换为单长度值的对象...

newData = {};
for(key in data[0]){
    parentKey = key;
    if(typeof(data[0][key]) == "object"){
       childData = data[0][key];
       for(key in childData){
          childKey = key;
          newKey = parentKey+childKey;
          newData[newKey] = childData[childKey];
       }
    } else {
       newData[key] = data[0][key];
      }
}

这将转换您的data对象

newData = {Id: 40072, Id2: 40071, SmDetailsId1: 40071, SmDetailsId2: 40072};

现在使用此newData在网格中映射您的数据项

答案 2 :(得分:-1)

我发现这适用于嵌套属性,例如:

var columns = [
    { id: "someId", name: "Col Name", field: "myRowData.myObj.myProp", width: 40}
..
];

var options {
...
dataItemColumnValueExtractor: function getItemColumnValue(item, column) {
    var val = undefined;
    try {
        val = eval("item." + column.field);
    } catch(e) {
        // ignore
    }
    return val;
    }
};