Fofole Fofole - 1 month ago 8
AngularJS Question

Angular js table with columns determined by object data

I have a list that contains objects that have variable data:

Object.id = 0;
Object.map1 = [{key, value}, {key,value}, ...]


What I have is the unchanged data(like the ID) which I put as a column and then it's value in the row.

However, all the keys from the map need to be columns as well with the mapped value in the respective row for them, because each request to the service can return different data. So the output should be something like:

ID KEY1 KEY2 ...
ID.VALUE VALUE1 VALUE2 ...
...


I'm new to angular hope this makes sense.

EDIT: What I've been trying for columns:

<thead>
<th ng-repeat="(column,v) in List.Objects[0].map1">
<a href="">{{column}}</a></th>
</th>
</thead>

Answer

I tried my best to understand what you need, and I've come up with this example, I hope it answered your question:

angular.module('MyApp', []).controller('MyCtrl', function($scope) {

  $scope.List = [{
    id: 1,
    map1: [{
      key: 'key1',
      value: '789'
    }, {
      key: 'key2',
      value: '987'
    }]
  }, {
    id: 2,
    map1: [{
      key: 'key1',
      value: 'bbb'
    }, {
      key: 'key2',
      value: 'ddd'
    }]
  }];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<table ng-app='MyApp' ng-controller='MyCtrl'>
  <tr>
    <th>
      id
    </th>
    <th ng-repeat="(column,v) in List[0].map1">
      {{v.key}}
    </th>
  </tr>
  <tr ng-repeat="map in List">
    <td>
      {{map.id}}
    </td>
    <td ng-repeat="(column,v) in map.map1">
      {{v.value}}
    </td>
  </tr>
</table>