sameera207
sameera207

Reputation: 16629

AngularJS select array hash element by name/value

I have the following angular array for one of my select tags

var names= [{name: 'Superman', val: '1'}, {name: 'Batman', val: '2'}];
$scope.names =names;
$scope.FormData = {};
$scope.FormData.name = $scope.names[1];

In the above array, instead of selecting the item by index (1), how can I select the item by name or the val, like

$scope.FormData.name = $scope.names['2']; #will select the {name: 'Batman', val: '2'}

I initially posted a lengthy question here, but then I realized this is the more simpler / focus way of my question

Upvotes: 1

Views: 3172

Answers (4)

Mik378
Mik378

Reputation: 22171

In the above array, instead of selecting the item by index (1), how can I select the item by name

You can use the find method of the Lodash library (http://lodash.com/docs#find):

var names= [{name: 'Superman', val: '1'}, {name: 'Batman', val: '2'}];

var matchingBatman = _.find(names, { name: 'Batman' });

matchingBatman is: {name: 'Batman', val: '2'}

You can do the same if you want to find by val:

var matchingBatman = _.find(names, { val: '2' });

Upvotes: 2

Leo Farmer
Leo Farmer

Reputation: 7900

If you want a re-useable function you could do it like this:

$scope.find = function(list, attributeName, attributeValue){
    var returnVal = {};
    angular.forEach(list,function(item){
        if(item[attributeName]){
          if(item[attributeName] === attributeValue){
            returnVal = item;
          }
        }
    });
    return returnVal;
};

$scope.FormData.name = $scope.find(names,'name','Batman');

Upvotes: 2

Josep
Josep

Reputation: 13071

If you are using angular, why not use the build in $filter?

https://docs.angularjs.org/api/ng/filter/filter

In your case, if you want to filter in the controller, the code bellow will retrieve an Array with all the occurrences inside names that match the search for 'Superman':

$filter('filter')($scope.names, {name:'Superman'})

If you are confident that there will be at least one match you could do this in order to get the first match:

var matches = $filter('filter')($scope.names, {name:'Superman'});
var match = matches[0]:

Bare in mind that if there are no matches then match will be undefined

Upvotes: 7

Sridhar Chidurala
Sridhar Chidurala

Reputation: 576

If you want to write a function instead of using a library

function selectByProperty(key, val){

    for(var i=0; i< $scope.names.length; i++){
        if($scope.names[i][key] === val){
           return $scope.names[i];
         }
     }

}
$scope.FormData.name  = selectByProperty('val','2');

Upvotes: 0

Related Questions