如何从具有id的数组中获取多个对象?

时间:2015-01-08 13:17:45

标签: javascript angularjs

我坚持使用Javascript基础知识。在Angular中工作。

我有一个包含对象的数组:

 $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提前!

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

您不断覆盖结果,因为它不是数组。试试这个:

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

答案 2 :(得分:0)

而不是分配你需要将该对象推送到数组

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

答案 3 :(得分:0)

$ scope.result不是数组..

您必须声明var result = [];,然后才能result.push($scope.persons[i]);

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

编辑:没用也将x分配给$ scope;另外还有一个jsfiddle

jsfiddle