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

How to get multiple objects from an array with an id?

本文关键字:获取 对象 数组 id      更新时间:2023-09-26

我坚持Javascript基础知识。在角度中工作。

我有一个带有对象的数组:

 $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 的所有对象?

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

提前感谢!

您可以使用过滤器

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

或者,在您的情况下,您需要在循环之前将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;
 };

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

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

而不是

分配,你需要将该对象推送到数组

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

$scope.result 不是一个数组。

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

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

编辑:无用也分配X给$scope; 添加了阿尔斯·

斯菲德尔