3

I've simplified this as much as possible. I'm 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 that array based on the value of name. Obviously what I have written below is wrong but the result of it is what I want.

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

Is there an angular feature I can use to go about this that will avoid me having to create a for loop or hash map?

2
  • 1
    {{ (myArrayOfValues | filter : {name: 'name2' })[0].extra }} Commented May 23, 2015 at 6:22
  • Thank you @doogabides! This was the easiest to use. You should write it as an answer. Commented May 23, 2015 at 6:31

2 Answers 2

5

You want to use a 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 search for 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 an exact match. You can leave the last parameter off or set it to false for a case insensitive substring search.

Sign up to request clarification or add additional context in comments.

Comments

2

I think the best way it to create a filter

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 could use it on this way

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

or maybe just format your json in another way to use it the way 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.


Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.