【问题标题】:AngularJS: Sort by date in ng-repeat where key is dateAngularJS:在 ng-repeat 中按日期排序,其中键是日期
【发布时间】:2016-10-05 13:01:02
【问题描述】:

我正在使用 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);
};

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

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

问题是,当我在前端显示它时,按月份分组的第一个 ng-repeat monthName 将按字母顺序排列(显示 August-July-September-October),到目前为止我还没有弄清楚如何按日期订购。

下面是 ng-repeat 的样子:

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

    {{monthName}}

</div>

当日期是对象的关键时,有什么方法可以使用orderBy:date

编辑

这个问题不再重复,因为我的问题是需要将键标识为日期,然后按它排序。我无法通过引用问题的答案解决此问题。

【问题讨论】:

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


【解决方案1】:

不能依赖 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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多