2015-01-08 2 views
0

자바 스크립트의 기초가 붙어 있습니다. 각도로 작업.ID가있는 배열에서 여러 객체를 가져 오는 방법은 무엇입니까?

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

내가 userId를과 같은 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.push($scope.persons[i]); 
0

아니라 할당보다 배열이 아닌 ..

당신이 선언해야 a var result = []; 그리고 나서 할 수있다 result.push($scope.persons[i]);

내가 왜 사용하고 있는지 모른다 $scope.result,이 목적을 위해 $ scope 및 watcher 속성을 인스턴스화하는 것은 쓸모가 없습니다. imho

편집 : 쓸모가 없습니다. $ scope에 x를 할당하십시오. 그 외에도 추가로

jsfiddle

0

$의 scope.result에 해당 객체를 밀어 필요

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

관련 문제