计算AngularJS中包含特定属性的对象

时间:2014-11-08 17:49:38

标签: javascript angularjs

我正在尝试从一组看起来像这样的对象中读取统计数据:

{
    "time":"19.09",
    "car":"429",
    "driver":"Julia",
    "from":"James Hotel",
    "destination":"Juba Teaching Hospital",
    "pax":"2",
    "arrival":"19.09",
    "inserted":true
}

{
    "date":"25/10/2014",
    "time":"19.11",
    "car":"396",
    "driver":"Tom",
    "from":"Drilling company",
    "destination":"James Hotel",
    "pax":"2",
    "comment":"This comment is a test",
    "commenttime":"19.11",
    "arrival":"19.12",
    "inserted":true
}

我正在使用AngularUI中的Unique模块来制作所有驱动程序或所有汽车的列表,到目前为止工作正常并创建下表:

table of stats

<div class="row msf-stats-data-row" >
  <div class="col-md-5">
    <div class="row" ng-repeat="record in recordlist | unique:'car'">
      <div class="col-md-4">{{record.car}}</div>
      <div class="col-md-4">Trips</div>
      <div class="col-md-4">Time on the road</div>
    </div>
  </div>

  <div class="col-md-6 pull-right">
    <div class="row"   ng-repeat="record in recordlist | unique:'driver'">
      <div class="col-md-6">{{record.driver}}</div>
      <div class="col-md-2">Trips</div>
      <div class="col-md-4">Time on the road</div>
    </div>
  </div>
</div>

每个物体都是旅行。我现在的问题是,我希望能够统计有多少个对象包含每个独特的record.carrecord.driver属性(以便能够确定汽车的行程数),以及使用momentJS进行操作,以确定特定汽车或司机在路上的时间(timeOnRoad = record.time - record.arrival)。

我是否有可能做到这一点有点迷失。

任何输入?

ANSWER

Ilan的答案完美无缺!在我稍微调整之后,这是我的代码。

var carsDict = {};

angular.forEach($scope.recordlist, function(record) {
  carsDict[record.car] = carsDict[record.car] || [];
  carsDict[record.car].push(record);
});
$scope.carstats = carsDict;

HTML:

 <div class="col-md-5">
        <div class="row" ng-repeat="carcode in carstats">
          <div class="col-md-4">{{carcode[0].car}}</div> <!-- Car code -->
          <div class="col-md-4">{{carcode.length}}</div> <!-- Nº of objects (trips) inside carcode -->
          <div class="col-md-4">Time on the road</div>
        </div>
 </div>

1 个答案:

答案 0 :(得分:3)

首先创建一个汽车词典来存储每辆车的记录参考。

var carsDict = {};

angular.forEach(recordlist, function(record) {
  carsDict[record.car] = carsDict[record.car] || [];
  carsDict[record.car].push(record);
});

然后你可以为每辆车进行所有计算。