2015-01-08 48 views
0

我坚持使用Javascript基础知识..在Angular中工作。如何从具有ID的数组中获取多个对象?

我有对象的数组:

$scope.persons = [ 
    { 
    id: 1, 
    name:'jack' 
    }, 
    { 
    id: 2, 
    name:'John' 
    }, 
    { 
    id: 3, 
    name:'eric' 
    }, 
    { 
    id: 2, 
    name:'John' 
    } 
] 

我想获得的是与用户id相同ID的所有对象。因此,如果对象ID与用户ID相匹配,则通过对象循环选择它。

$scope.getResult = function(userId){ 
    $scope.userId = userId; 

    for(var i=0;i < $scope.persons.length; i++){ 

    if($scope.persons[i].id === $scope.userId){ 
     $scope.result = $scope.persons[i]; 
    } 
    } 
    $scope.userLogs = $scope.result; 
}; 

我在这里只得到与userId具有相同id的最后一个对象。

如何列出与userId具有相同ID的所有对象?

直播:http://jsfiddle.net/sb0fh60j/

日Thnx提前!

回答

1

您可以使用filter

$scope.getUsers = function(x){ 
    $scope.userId = x; 

    $scope.userLogs = $scope.persons.filter(function (person) { 
     return person.id === x; 
    }) 
}; 

Example

或者,你的情况,你需要声明result作为循环前阵,并加入比赛吧,这样

$scope.getUsers = function(x){ 
    $scope.userId = x; 
    $scope.result = []; 

    for(var i=0;i < $scope.persons.length; i++){ 

    if($scope.persons[i].id === $scope.userId){ 
     $scope.result.push($scope.persons[i]); 
    } 
    } 
    $scope.userLogs = $scope.result; 
}; 

Example

0

由于它不是数组,所以你总是覆盖你的结果。试试这个来代替:

$scope.result[] = $scope.persons[i];

0

,而不是分配你需要该对象推到阵列

$scope.result.push($scope.persons[i]); 
0

$ scope.result不是一个数组..

必须声明一个var result = [];然后你可以做result.push($scope.persons[i]);

我不明白你为什么用$scope.result,实例化$ scope和它的观察者的属性为此目的是没有用的,imho

edit:is useless也指定x为$ scope; ALSE添加一个的jsfiddle

jsfiddle

相关问题