AngularJs - 将2个类似键的数组合并为1 ng-repeat

时间:2015-10-12 03:13:09

标签: javascript arrays angularjs

我有以下两个对象数组。

数组1:估计小时数($scope.estimated_hours

[
  {
    "total_hours_spent_on_role": "56.00",
    "job_role": "Installing"
  },
  {
    "total_hours_spent_on_role": "46.00",
    "job_role": "Electrical"
  },
  {
    "total_hours_spent_on_role": "4.00",
    "job_role": "Delivery"
  },
  {
    "total_hours_spent_on_role": "2.00",
    "job_role": "Supervision"
  },
  {
    "total_hours_spent_on_role": "2.00",
    "job_role": "Commissioning"
  }
]

数组2:实际小时数($scope.actual_hours

[
  {
    "job_role": "Electrical",
    "total_hours_spent_on_role": "21.00"
  },
  {
    "job_role": "Installing",
    "total_hours_spent_on_role": "5.50"
  }
]

现在我想用ng-repeat输出与此类似的东西,但还没有运气好。

Installing: 5.50 (Act. Hours) / 56.00 (Est. Hours)

Electrical: 21.00 (Act. Hours) / 45.00 (Est. Hours)

Delivery: 0.00 (Act. Hours) / 4.00 (Est. Hours)

Supervision: 0.00 (Act. Hours) / 2.00 (Est. Hours)

Commissioning: 0.00 (Act. Hours) / 2.00 (Est. Hours)

我们如何将2个数组合并为1 ng-repeat?我通常避免使用逻辑将它们合并在一起。

1 个答案:

答案 0 :(得分:3)

这有帮助吗?



var arr1 = [{
    "total_hours_spent_on_role": "56.00",
    "job_role": "Installing"
  }, {
    "total_hours_spent_on_role": "46.00",
    "job_role": "Electrical"
  }, {
    "total_hours_spent_on_role": "4.00",
    "job_role": "Delivery"
  }, {
    "total_hours_spent_on_role": "2.00",
    "job_role": "Supervision"
  }, {
    "total_hours_spent_on_role": "2.00",
    "job_role": "Commissioning"
  }
];


var arr2 = [{
  "job_role": "Electrical",
  "total_hours_spent_on_role": "21.00"
}, {
  "job_role": "Installing",
  "total_hours_spent_on_role": "5.50"
}];

var app = angular.module("myapp", [])

.controller("arrCtrl", ["$scope",
  function($scope) {
    $scope.arr = arr1;
    $scope.getArr2ValByKey = function(key) {
      var val = arr2.filter(function(i) {

        return i.job_role == key.job_role;
      }).map(function(a) {
        console.log(a);
        return a.total_hours_spent_on_role;
      })[0];
      return val || 0.0;
    }
  }
]);

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp">
  <div ng-controller="arrCtrl">
    <ul>
      <li ng-repeat="a in arr">{{a.job_role}} : (Act hours){{getArr2ValByKey(a)}} / {{a.total_hours_spent_on_role}} (Act hours)</li>
    </ul>
  </div>
</div>
&#13;
&#13;
&#13;