In Angular, I need to search objects in an array

JavascriptAngularjs

Javascript Problem Overview


In Angular, I have in scope a object which returns lots of objects. Each has an ID (this is stored in a flat file so no DB, and I seem to not be able to user ng-resource)

In my controller:

$scope.fish = [
    {category:'freshwater', id:'1', name: 'trout', more:'false'},
    {category:'freshwater', id:'2', name:'bass', more:'false'}
];

In my view I have additional information about the fish hidden by default with the ng-show more, but when I click the simple show more tab, I would like to call the function showdetails(fish.fish_id). My function would look something like:

$scope.showdetails = function(fish_id) {  
    var fish = $scope.fish.get({id: fish_id});
    fish.more = true;
}

Now in the the view the more details shows up. However after searching through the documentation I can't figure out how to search that fish array.

So how do I query the array? And in console how do I call debugger so that I have the $scope object to play with?

Javascript Solutions


Solution 1 - Javascript

You can use the existing $filter service. I updated the fiddle above http://jsfiddle.net/gbW8Z/12/

 $scope.showdetails = function(fish_id) {
     var found = $filter('filter')($scope.fish, {id: fish_id}, true);
     if (found.length) {
         $scope.selected = JSON.stringify(found[0]);
     } else {
         $scope.selected = 'Not found';
     }
 }

Angular documentation is here http://docs.angularjs.org/api/ng.filter:filter

Solution 2 - Javascript

I know if that can help you a bit.

Here is something I tried to simulate for you.

Checkout the jsFiddle ;)

http://jsfiddle.net/migontech/gbW8Z/5/

Created a filter that you also can use in 'ng-repeat'

app.filter('getById', function() {
  return function(input, id) {
    var i=0, len=input.length;
    for (; i<len; i++) {
      if (+input[i].id == +id) {
        return input[i];
      }
    }
    return null;
  }
});

Usage in controller:

app.controller('SomeController', ['$scope', '$filter', function($scope, $filter) {
     $scope.fish = [{category:'freshwater', id:'1', name: 'trout', more:'false'},  {category:'freshwater', id:'2', name:'bass', more:'false'}]
     
     $scope.showdetails = function(fish_id){
         var found = $filter('getById')($scope.fish, fish_id);
         console.log(found);
         $scope.selected = JSON.stringify(found);
     }
}]);

If there are any questions just let me know.

Solution 3 - Javascript

To add to @migontech's answer and also his address his comment that you could "probably make it more generic", here's a way to do it. The below will allow you to search by any property:

.filter('getByProperty', function() {
    return function(propertyName, propertyValue, collection) {
        var i=0, len=collection.length;
        for (; i<len; i++) {
            if (collection[i][propertyName] == +propertyValue) {
                return collection[i];
            }
        }
        return null;
    }
});

The call to filter would then become:

var found = $filter('getByProperty')('id', fish_id, $scope.fish);

Note, I removed the unary(+) operator to allow for string-based matches...

Solution 4 - Javascript

A dirty and easy solution could look like

$scope.showdetails = function(fish_id) {
	angular.forEach($scope.fish, function(fish, key) {
		fish.more = fish.id == fish_id;
	});
};

Solution 5 - Javascript

Angularjs already has filter option to do this , https://docs.angularjs.org/api/ng/filter/filter

Solution 6 - Javascript

Your solutions are correct but unnecessary complicated. You can use pure javascript filter function. This is your model:

     $scope.fishes = [{category:'freshwater', id:'1', name: 'trout', more:'false'},  {category:'freshwater', id:'2', name:'bass', more:'false'}];

And this is your function:

     $scope.showdetails = function(fish_id){
         var found = $scope.fishes.filter({id : fish_id});
         return found;
     };

You can also use expression:

     $scope.showdetails = function(fish_id){
         var found = $scope.fishes.filter(function(fish){ return fish.id === fish_id });
         return found;
     };

More about this function: LINK

Solution 7 - Javascript

Saw this thread but I wanted to search for IDs that did not match my search. Code to do that:

found = $filter('filter')($scope.fish, {id: '!fish_id'}, false);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontsporeView Question on Stackoverflow
Solution 1 - JavascriptAdrian GunawanView Answer on Stackoverflow
Solution 2 - JavascriptmigontechView Answer on Stackoverflow
Solution 3 - JavascriptherringtownView Answer on Stackoverflow
Solution 4 - JavascriptArun P JohnyView Answer on Stackoverflow
Solution 5 - JavascriptMd Imranur RahmanView Answer on Stackoverflow
Solution 6 - JavascriptMichał JarzynaView Answer on Stackoverflow
Solution 7 - JavascriptOgglasView Answer on Stackoverflow