如何在angularJS中从2个不同的字符串和数字数组创建对象数组? 例如:
$scope.array1=['sale1','sale2','sale3']
$scope.array2=[2,3,4]
从这两个数组我希望将一个数组作为
$scope.resultArray=[
{'key':'sale1','value':2},
{'key':'sale2','value':3},
{'key':'sale3','value':4}
]
答案 0 :(得分:1)
您可以执行以下操作:
for (var i = 0; i < $scope.array1.length; i++) {
$scope.resultArray.push({
'key': $scope.array1[i],
'value': $scope.array2[i]
});
}
代码段正在运作:
(function() {
'use strict';
angular.module('app', [])
.controller('mainCtrl', function($scope) {
$scope.array1 = ['sale1', 'sale2', 'sale3'];
$scope.array2 = [2, 3, 4];
$scope.resultArray = [];
for (var i = 0; i < $scope.array1.length; i++) {
$scope.resultArray.push({
'key': $scope.array1[i],
'value': $scope.array2[i]
});
}
});
})();
<!DOCTYPE html>
<html ng-app="app">
<head><script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>
<body ng-controller="mainCtrl">
<div ng-repeat="obj in resultArray track by $index">
<span ng-bind="obj.key + ' - ' + obj.value"></span>
</div>
</body>
</html>
答案 1 :(得分:0)
使用下划线zip
$scope.array1=['sale1','sale2','sale3']
$scope.array2=[2,3,4]
$scope.resultArray = _.zip($scope.array1, $scope.array2)
答案 2 :(得分:-1)
for(var i=0;$scope.array1.length>i;i++){
$scope.resultArray.push({$scope.array1[i]:$scope.array2[i]});
}