Joey Zhang Joey Zhang - 6 months ago 16
AngularJS Question

How to find an array object according to given information?

I have an array in AngularJS controller like this:

$scope.persons = [{name:'Joey', age:'27'},{name:'Lucy', age:'22'}]


I have got a name 'Lucy', how can I get the age of the name in the controller (not in HTML)?

Answer

I've created a plunk here that outlines a single result, with just the age, as well as multiple results.

This could also be implemented within a filter, which is documented on the Angular site here: https://docs.angularjs.org/api/ng/filter/filter

https://plnkr.co/edit/OFRMzpQrZfTOnaFyJP7Z?p=info

angular.module('plnk',[]).controller('plnkCtrl', function($scope){

  // Note, I added a second Joey here to test the multiple function.
  // For output, check the browser console.

  $scope.persons = [{name:'Joey', age:'27'},{name:'Joey', age:'28'},{name:'Lucy', age:'22'}]

  console.log('Single -> ', getAgeSingle('Lucy'));
  console.log('Multiple ->',getAgeMultiple('Joey'));

  function getAgeMultiple(personLookup) {

    var results = [];
    angular.forEach($scope.persons,function(person){
       if (person.name === personLookup) {
         results.push(person);
         // or results.push(person.age) for age only
       }
     });
    return results;

  }

  function getAgeSingle(personLookup) {
    var result = '';
    angular.forEach($scope.persons,function(person){
       if (person.name === personLookup && !result) {
         result = person.age;
       }
     });
    return result;
  }

});