Angularjs | Finding JsonArray for a specific value

I have simplified this as much as possible. I am using angularjs, I have a controller with an array of json objects like this:

controller('simpleC', function ($scope) {

  $scope.myArrayOfValues = [
    {
       "name" : "name1",
       "extra": "data"
    },
    {
       "name" : "name2",
       "extra": "data"
    },
    {
       "name" : "name3",
       "extra": "data"
    }
  ];
});

      

In my html view, I want to quickly find a specific json object from this array based on the name value. Obviously what I have written below is not correct, but the result of this is what I want.

<div ng-show="myArrayOfValues['name2']"></div>

      

Is there an angular function I can use to get around this to avoid having to create a for loop or hash?

+3


source to share


2 answers


You want to use filter . Let's say you have a list.

<ul>
  <li ng-repeat="item in myArrayOfValues">{{item.name}}</li>
</ul>

      

Now, let's say you want to find a name using an exact match.



<input ng-model="search.name"><br>
<ul>
  <li ng-repeat="item in myArrayOfValues | filter:search:true">{{item.name}}</li>
</ul>

      

The last parameter true

is what makes it accurate. You can leave the last option off or set it to false to search for a case insensitive substring.

+5


source



I think the best way to create a filter is

app.filter('getObj', [
    function() {
        return function(input,val) {
            var r,i;
            for(i; i<input.length;i++) {
                if (input[i].name === val) {
                   r = input[i];
                   break;
                }
            };
            return r;
        };
    }
]);

      

then you can use it along the way

<div ng-show="myArrayOfValues|getObj('name2')"></div>

      

or maybe just format your json differently to use it however you like



  $scope.myArrayOfValues = {
       name1 :  {
           "name" : "name1",
           "extra": "data"
        },
        name2 : {
           "name" : "name2",
           "extra": "data"
        },
        name3 : {
           "name" : "name3",
           "extra": "data"
        }
      };

      

and

<div ng-show="myArrayOfValues['name2']"></div>

      

will work fine.


+2


source







All Articles