实际上有一个简单的解决方案......默认情况下对象键没有排序但是如果您从头开始在浏览器中创建对象,您的浏览器将知道顺序;)
例子:
// test-1
var data = {};
data['a'] = 10;
data['b'] = 5;
data['c'] = 2;
Object.keys(data); // ["a", "b", "c"]
// test-2
var data = {};
data['b'] = 5;
data['a'] = 10;
data['c'] = 2;
Object.keys(data); // ["b", "a", "c"]
所以很简单......重新创建对象......或使用这个简单的过滤器:
.filter('orderObject', function () {
return function (object, reverse) {
var keys = Object.keys(object || {}).sort();
if (reverse) keys.reverse();
for (var ordered = {}, i = 0; keys[i]; i++) {
ordered[keys[i]] = object[keys[i]];
}
return ordered;
}
})
常规对象的示例:
<!-- MARKUP : DEFAULT -->
<table>
<tr ng-repeat="(key, value) in data">
<td>{{key}}</td>
<td>{{value}}</td>
</tr>
</table>
<!-- RESULT : test-1 -->
<table>
<tr>
<td>a</td>
<td>10</td>
</tr>
<tr>
<td>b</td>
<td>5</td>
</tr>
<tr>
<td>c</td>
<td>2</td>
</tr>
</table>
<!-- RESULT : test-2 -->
<table>
<tr>
<td>b</td>
<td>5</td>
</tr>
<tr>
<td>a</td>
<td>10</td>
</tr>
<tr>
<td>c</td>
<td>2</td>
</tr>
</table>
排序对象的示例:
<!-- MARKUP : with FILTER orderObject:<reverse?> -->
<table>
<tr ng-repeat="(key, value) in data | orderObject">
<td>{{key}}</td>
<td>{{value}}</td>
</tr>
</table>
<!-- RESULT : test-1 without reverse -->
<table>
<tr>
<td>a</td>
<td>10</td>
</tr>
<tr>
<td>b</td>
<td>5</td>
</tr>
<tr>
<td>c</td>
<td>2</td>
</tr>
</table>
<!-- RESULT : test-2 with reverse -->
<table>
<tr>
<td>c</td>
<td>2</td>
</tr>
<tr>
<td>b</td>
<td>5</td>
</tr>
<tr>
<td>a</td>
<td>10</td>
</tr>
</table>