![](/img/trans.png)
[英]JavaScript - Combine and Add Values in Multiple Same Length Object Arrays
[英]AnguarJS/ javascript combine two arrays with same length together
我正在尝试将两个具有相同长度的数组组合在一起array1(用户数组)是一个用户列表。array2(布尔数组)是从HTTP状态(如果成功= true /如果错误为false)生成的布尔值的列表。知道它的设置有点奇怪,但这就是支持的开发人员提供的。.只需要利用他提供的..为了简洁起见,GetUseFollowers服务的数据模型返回to_id和from_id,这就是为什么我没有getUserById的原因。
资料模型:
$scope.users = [{id:1, username="foo"}, {id:2, username="bar"}];
$scope.check = [{true,false}]; //there is no key does it even count as an array?
所需的输出:
$scope.users = [{id:1, username="foo", is_following: true},{id:2, username="bar", is_following: false}]
$scope.check = []; // array with boolean values
var checkIfFollowing= function(id){
UserService.CheckIfFollowing($stateParams.id, id,)
.success(function (data) {
var check = true;
$scope.check.push(check);
}).
error(function(error, status) {
var check = false;
$scope.check.push(check);
});
}
$scope.users = []; // users array
var getUser = function(id) {
UserService.GetUserById(id, $localStorage.CurrentUser.auth_token)
.success(function (data) {
$scope.data = angular.fromJson(data);
$scope.users.push($scope.data);
$scope.$broadcast('scroll.refreshComplete')
console.log(angular.toJson($scope.users));
}).error(function(error, status) {
alert(status);
console.log(error);
});
};
$scope.GetUserFollowers = function() {
UserService.GetUserFollowers($stateParams.id, -1, 0, 6)
.success(function (data) {
console.log(data);
data = angular.fromJson(data);
angular.forEach(data, function(user){
checkIfFollowing(user.from_user) //create array check
getUser(user.from_user) //create array users
});
}).
error(function(error, status) {
alert(status);
console.log(error);
});
}
您可以使用Array.map()
合并这些数组。 这是一个没有Angular的简单示例。
var users = [{id:1, username:"foo"}, {id:2, username:"bar"}]; var check = [true,false]; var merged = users.map(function(value, index) { var newValue = value; newValue.is_following = check[index]; return newValue; }); console.log(merged);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.