AngularJS:在ng-repeat中按日期排序,其中键是日期

时间:2016-10-05 13:01:03

标签: javascript angularjs date angularjs-ng-repeat lodash

我使用LoDash从IndexedDB中的某些记录创建统计信息。

$scope.refreshStats = function() {

    var dataByMonth = _.groupBy($scope.stats, function(record) { 
        return moment(record.date).format('MMMM YYYY'); 
    });

    dataByMonth = _.mapValues(dataByMonth, function(month) {
        var obj = {};
        obj.Cars = _.groupBy(month, 'car');
        obj.Drivers = _.groupBy(month, 'driver');

        _.each(obj, function(groupsValue, groupKey) {
            obj[groupKey] = _.mapValues(groupsValue, function(groupValue) {
                return _.reduce(groupValue, function(sum, trip) {
                    sum['trips']++;
                    sum['duration']+= moment.utc(trip.duration, 'HH:mm:ss');
                    sum['total'] = moment.utc(sum.duration). format('HH:mm:ss')
                    return sum;
                }, {trips: 0, duration: 0, total:0})
            });
        })
        return obj;
    });
    $scope.statistics = dataByMonth;
    console.log($scope.statistics);
};

我的函数的结果是嵌套对象的集合,其中key始终是一个月和一年:

Object {
    July 2016: Object, 
    August 2016: Object, 
    September 2016: Object, 
    October 2016: Object
}

问题在于,当我在前端显示它时,按月monthName分组的第一个ng-repeat将按字母顺序排列(显示8月 - 7月 - 9月 - 10月),到目前为止我没有&#39 ;弄清楚如何按日期订购。

以下是ng-repeat的样子:

<div ng-repeat="(monthName, monthValue) in statistics">

    {{monthName}}

</div>

当日期是对象的键时,有没有办法使用orderBy:date

修改

问题没有重复,因为我的问题是需要将密钥标识为日期,然后按顺序排序。我还没有能够用所提问题的答案来解决这个问题。

1 个答案:

答案 0 :(得分:2)

不能依赖JS中对象的键顺序,您必须将数据转换为{date:,value:}对象并对其进行排序。

第一步,转换:

var step1 = _.map(_.pairs(dataByMonth), _.partial(_.zipObject, ['date', 'value'] ));

接下来你需要对它们进行排序:

var step2 = _.sortBy(step1, function(value){
  return new Date(value.date);
});

step2保存您的排序值

$scope.statistics = step2;

你可以在ng-repeat中使用它

<div ng-repeat="montStats in statistics">

    {{monthStats.date}}

</div>

您可以通过以下方式进一步优化代码:

将日期保留为实际日期,并避免按每次排序迭代进行解析。

将操作链接起来:

_(dataByMonth).pairs().map(
  _.partial(_.zipObject, ['date', 'value'])).sortBy(function(value){
    return new Date(value);
  }).value();
相关问题