如何用 AngularJS 遍历对象的 'key' 值?

How to loop through the 'key' value of an object with AngularJS?

我有以下数据和 HTML 模板(显然还有 app.js 中的其他代码)。我的 "tbody" 中的代码运行完美,并显示 table 如下:

当前输出

--------------------
| AAPL | 127 | 128 |
--------------------
| GOOG | 523 | 522 |
--------------------
| TWTR |  35 |  36 |
--------------------

现在我尝试遍历第一个对象的 'keys' 并将它们显示在 'thead' 中,如下所示:

期望输出

--------------------
| Name | jan | feb |
--------------------
| AAPL | 127 | 128 |
--------------------
| GOOG | 523 | 522 |
--------------------
| TWTR |  35 |  36 |
--------------------

数据

$scope.data = [
{  
    "name": "AAPL",
    "jan": "127",
    "feb": "128"
},
{
    "name": "GOOG",
    "jan": "523",
    "feb": "522"
},
{
    "name": "TWTR",
    "jan": "35",
    "feb": "36"
}]

html

<table>
    <thead>
        <tr>
            <td ng-repeat="">{{}}</td>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="object in data">
            <td ng-repeat="(a,b) in object">{{b}}</td>
        </tr>
    </tbody>
</table>

有人指出这个问题与另一个问题重复,尽管另一个问题是纯 JS,这个问题使用 AngularJS。

如果您使用 underscoreJS(这是一个非常常见且功能强大的便利库),那么第一个对象的 you can get the keys 如下所示:

_.keys(data[0])

这假定数组中的所有元素都具有相同的键和结构。看起来像,所以你应该是安全的。

在您的应用程序中包含 UnderscoreJS 之后,您可以从方括号表达式中的模板调用它:

 <td ng-repeat="">{{ _.keys(data[0])}}</td>

纯 ES5 解决方案

如果你不喜欢一个库,并且你可以接受 ES5,那么你可以使用

Object.keys(data[0])
<td ng-repeat="">{{ Object.keys(data[0]) }}</td>

You use use Angular's (key, value) syntax. 但是,我认为这对您的情况不起作用,因为迭代顺序是随机的。

我认为最好的办法是在 $scope.headings 变量中对键进行硬编码或更新数据格式(如果您可以控制数据的生成方式),以便键的顺序是指定。

<td ng-if="data.length" ng-repeat="(a,b) in data[0]">{{a}}</td>

您只需要考虑键值总是以相同的顺序出现,否则 table 将以错误的顺序显示值。

@murid,你需要这个吗:

在头部的脚本标签中:

var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
    $scope.data = [{
        "name": "AAPL",
            "jan": "127",
            "feb": "128"
    }, {
        "name": "GOOG",
            "jan": "523",
            "feb": "522"
    }, {
        "name": "TWTR",
            "jan": "35",
            "feb": "36"
    }];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
    <table>
        <thead>
            <tr>
                <td ng-repeat="">{{}}</td>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="object in data">
                <td ng-repeat="(a,b) in object">{{b}}</td>
            </tr>
        </tbody>
    </table>
</div>

希望对您有所帮助。