user2769614 user2769614 - 1 month ago 9
AngularJS Question

UI-GRID Dynamic column headers and array of object data

I have following data

vm.myData =
{
'Type' :
[
'A',
'B',
'C'
],
'Data': [
{
'Key': 'XXX',
'AValues':
{
'ID': '1',
'Val': '10'
},
'BValues':
{
'ID': '2',
'Val': '20'
},
'CValues':
{
'ID': '2',
'Val': '20'
}
},
{
'Key': 'TTT',
'AValues':
{
'ID': '2',
'Val': '30'
},
'BValues':
{
'ID': '4',
'Val': '70'
},
'CValues':
{
'ID': '2',
'Val': '20'
}
}
]
};


I am trying to show data as below

Key A B C
XXX 10 20 20
TTT 30 70 20


I tried it many ways but not able to get desired result.
I want the name of the Columns to come from 'Type' on 'myData'.
I am able to display first row by hardcoding.

vm.gridOptions = {
columnDefs: [
{ name: 'Key', field: 'Data[0].Key'},
{ name: 'A', field: 'Data[0].AValues.Val'},
{ name: 'B', field: 'Data[0].BValues.Val'},
{ name: 'C', field: 'Data[0].CValues.Val'}
],
data: vm.myData
};


I would really appreciate any help.

Update
After going through Naren Mulrali's suggestion, I did following which gives me desired result.
But I have hardcoded column names(I need different display names).
Is there a way to dynamically get column header from the 'Type' array from 'myData'

vm.gridOptions = {
columnDefs: [
{ displayName: 'Key', name: 'Key' },
{ displayName: 'A', name: 'AValues.Val' },
{ displayName: 'B', name: 'BValues.Val' },
{ displayName: 'C', name: 'CValues.Val' }
],
data: vm.myData.Data
};

Answer Source

You need to convert your Object into a format that angular ui grid understands, please refer to the below JSFiddle

        angular.forEach($scope.myData.Data, function(value, index){
          value.AValues = value.AValues.Val;
          value.BValues = value.BValues.Val;
          value.CValues = value.CValues.Val;
          $scope.myData.Data[index] = value;
        });

JSFiddle: link