ramesh ramesh - 4 months ago 15
JSON Question

ng-repeat: render table based on json data

My json data looks something like this:

{'A': 'L', 'B': 'L', 'C': 'G', 'D': 'L', 'E': 'G', 'F': 'L' }


I want to draw table like this using ng-repeat,

L G
A C
B E
D
F


Here, I'm grouping
keys
based on
values
.

This is what I tried, but I'm not getting what I wanted.

<table class="table table-hover">
<thead>
<tr>
<th>L</th>
<th>G</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="(key, val) in intlist track by $index">
<td ng-if="val=='L'">{{ key }}</td>
<td ng-if="val=='K'">{{ key }}</td>
</tr>
</tbody>
</table>

Answer

Map data to new array of arrays that can be repeated, then repeat inside that for each cell

var app = angular.module('angularTest', []);

app.controller('MainCtrl', ['$scope',
  function($scope) {
    var data = {'A': 'L', 'B': 'L', 'C': 'G', 'D': 'L', 'E': 'G', 'F': 'L' };
    
    var tmp = {};
    // map values to arrays of keys in tmp
    for (var key in data) {
      if (!tmp[data[key]]) {
        tmp[data[key]] = []
      }
      tmp[data[key]].push(key)

    }
    // create array of headings from `tmp` keys
    var headings = Object.keys(tmp);
    // get longest array
    var res = headings.reduce(function(a, c) {
      return tmp[c].length > a.length ? tmp[c] : a
      // use longest to map results array
    }, []).map(function(_, i) {
      return headings.map(function(heading) {           
        return tmp[heading][i] || '';
      });;
    });

    $scope.headings = headings;
    $scope.list = res;

  }
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.js"></script>
<div ng-app="angularTest" ng-controller="MainCtrl">
  <h4>List Data</h4>
  <pre>{{list}}</pre>
  <h4>View Table</h4>   
<table class="table table-hover" border="1">
  <thead>
    <tr>
      <th  ng-repeat="heading in headings">{{heading }}</th>          
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="arr in list">
      <td ng-repeat="item in arr">{{item}}</td>
    </tr>

  </tbody>
</table>
</div>

Comments