基于值

时间:2015-11-14 19:42:38

标签: angularjs

我有一个以下的json结构,我想把它变成表格。

这里最好的方法是什么?第1组和第-1组分别代表正面和负面。这些可以或不可以在数据中显示,但必须在表中定义。

预期结果

           | Very Positive | Positive | Neutral | Negative | Very Negative |
-----------+---------------+----------+---------+----------+---------------|
Cleaniness |      16       |    0     |   11    |    0     |       30      |
Staff      |      20       |    0     |   15    |    0     |       37      |
-----------+---------------+----------+---------+----------+---------------|

数据:

{
  "Cleanliness": [
    {
      "group": "-2",
      "count": 30
    },
    {
      "group": "0",
      "count": 11
    },
    {
      "group": "2",
      "count": 16
    }
  ],
  "Staff": [
    {
      "group": "-2",
      "count": 37
    },
    {
      "group": "0",
      "count": 15
    },
    {
      "group": "2",
      "count": 20
    }
  ]
}

任何帮助表示感谢,提前谢谢!

1 个答案:

答案 0 :(得分:1)

您可以在固定数组值ng-repeat="pos in [2, 1, 0, -1, -2]"上使用ngRepeat:

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

app.controller('demoCtrl', function() {

  var stats = {
    "Cleanliness": [{
      "group": "-2",
      "count": 30
    }, {
      "group": "0",
      "count": 11
    }, {
      "group": "2",
      "count": 16
    }],
    "Staff": [{
      "group": "-2",
      "count": 37
    }, {
      "group": "0",
      "count": 15
    }, {
      "group": "2",
      "count": 20
    }]
  };

  /** we want to transform original data to this structure 
  [{
    name: "Cleanliness",
    data: {
      '-2': 30,
      '0': 11,
      '2': 16
    }
  }, {
    name: "Staff",
    data: {
      '-2': 37,
      '0': 15,
      '2': 20
    }
  }]
  **/

  this.stats = Object.keys(stats).map(function(category) {
    return {
      name: category,
      data: stats[category].reduce(function(obj, stat) {
        obj[stat.group] = stat.count;
        return obj;
      }, {})
    };

  });

});
table {
  border-collapse: collapse;
}
th,
td {
  padding: 0 3px;
  border: 1px solid blue;
}

td:not(:first-child) {
  text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="demo" ng-controller="demoCtrl as demo">

  <table>

    <thead>
      <tr>
        <th></th>
        <th>Very Positive</th>
        <th>Positive</th>
        <th>Neutral</th>
        <th>Negative</th>
        <th>Very Negative</th>
      </tr>
    </thead>

    <tbody>
      <tr ng-repeat="category in demo.stats">
        <td>{{category.name}}</td>
        <td ng-repeat="pos in [2, 1, 0, -1, -2]">
          {{category.data[pos] || 0}}
        </td>
      </tr>
    </tbody>

  </table>

</div>