如何按键排序为整数?
我有以下对象;
$scope.data = {
"0": { data: "ZERO" },
"1": { data: "ONE" },
"2": { data: "TWO" },
"3": { data: "TREE" },
"5": { data: "FIVE" },
"6": { data: "SIX" },
"10":{ data: "TEN" },
"11": { data: "ELEVEN" },
"12": { data: "TWELVE" },
"13": { data: "THIRTEEN" },
"20": { data: "TWENTY"}
}
HTML:
<div ng-repeat="(key,value) in data">
当前的输出订单为1,10,11,12,13,14,2,20,3,4,5,6
但我想要1,2,3,4,5,6,10,11,12,13,14,20
| orderBy:key
不适合我。
有什么想法吗?
谢谢!
答案 0 :(得分:19)
选项将使用中间过滤器。
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
$scope.template = {
"0": { data: "ZERO" },
"1": { data: "ONE" },
"2": { data: "TWO" },
"3": { data: "TREE" },
"5": { data: "FIVE" },
"6": { data: "SIX" },
"10":{ data: "TEN" },
"11": { data: "ELEVEN" },
"12": { data: "TWELVE" },
"13": { data: "THIRTEEN" },
"20": { data: "TWENTY"}
}
});
app.filter('toArray', function() { return function(obj) {
if (!(obj instanceof Object)) return obj;
return _.map(obj, function(val, key) {
return Object.defineProperty(val, '$key', {__proto__: null, value: key});
});
}});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore.js"></script>
<body ng-app="app" ng-controller="MainCtrl">
<div ng-repeat="(key, value) in template| toArray | orderBy:key">{{key}} : {{value.$key}} : {{value.data}}</div>
<body>
上面的过滤器需要Underscore.js,如果你不使用它,可以重写过滤器。
答案 1 :(得分:2)
我认为通过转换为数组可以自行解决问题。双关语。
var obj = {"3": {three:3}, 2: {two:2}, "5": {five:5}, 4: {four:4},
1: {one:1}, 6: {six:6}, 10: {ten:10}, 11:{eleven:11}
}
$scope.arr = [];
for (var o in obj)
$scope.arr.push(obj[o])
答案 2 :(得分:0)
app.filter('orderObjectBy', [function() {
return (filterObj, prop) => {
let arr = []
//below is the loadash function you can use for in also
_.forEach(filterObj, function(value, key) {
arr.push({
key: key,
value: value
});
});
let sortedArr = _.sortBy(arr, val => val.value[prop]);
for (let variableKey in filterObj) {
if (filterObj.hasOwnProperty(variableKey)) {
delete filterObj[variableKey];
}
}
for (let data of sortedArr) {
filterObj[data.key] = data.value;
}
return filterObj;
}
}])