简体   繁体   English

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

[英]How to get multiple objects from an array with an id?

I am stuck with Javascript basics.. Working in Angular. 我坚持使用Javascript基础。在Angular中工作。

I have an array with objects: 我有一个对象数组:

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

I would like to get the all objects that have same id with userId. 我想获得与userId具有相同ID的所有对象。 So, loop through objects if the object id matches to user id select it. 因此,如果对象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;
 };

I get here only the last object which has the same id with userId. 我在这里仅获得与userId具有相同ID的最后一个对象。

How do I list all the objects that have the same id with userId? 如何列出所有具有与id相同ID的对象?

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

Thnx in advance! 提前thnx!

You can use filter 您可以使用过滤器

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

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

Example

Or, in your case, you need declare result as array before loop, and add matches to it, like this 或者,在您的情况下,需要在循环之前将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

You are constantly overwriting your result as it is no array. 您将不断覆盖结果,因为它不是数组。 try this instead: 试试这个代替:

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

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

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

$scope.result is not an array.. $ scope.result不是数组。

you have to declare a var result = []; 您必须声明一个var result = []; and then you can do result.push($scope.persons[i]); 然后可以执行result.push($scope.persons[i]);

I don't understand why are you using $scope.result , it is useless to instantiate an attribute of the $scope and its watcher for this purpose, imho 我不明白为什么要使用$scope.result ,为此目的实例化$ scope及其监视程序的属性是没有用的

edit: is useless also assign x to $scope; 编辑:是无用的也分配x到$ scope; added alse a jsfiddle 还添加了一个jsfiddle

jsfiddle 的jsfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM