teddybear123
teddybear123

Reputation: 2424

AngularJS checking if a field within an object array exists

I have a data model like this:

var array =  [{id:1, name:"foo"}, {id:2, name:"bar"}, {id:3 name:"september"}];

I want to loop through the array and see if id:3 exists how do i do that?

Upvotes: 1

Views: 10352

Answers (5)

POZ
POZ

Reputation: 591

Just use an AngularJS filter, these are exactly made for that purpose:

var results = $filter('filter')(array, {id : 3}, true);

results will contain an an array of object(s) (there might be more than one) with an attribute id equal to 3.

If the length of results is zero then, there was no element matching the filter.
If you know, there is only one possible result you may retrieve it directly with results[0].

The advantage of using a filter is that you can easily filter on multiple attribute values by extending the filter expression {id : 3}.

Cheers,

Upvotes: 9

Sudhansu Choudhary
Sudhansu Choudhary

Reputation: 3360

Wonder, you are missing a , after id:3

It's more of a javaScript looping over an Array than an AngularJS way,

var array =  [{id:1, name:"foo"}, {id:2, name:"bar"}, {id:3, name:"september"}];

for(var i in array){
    if(array[i].id === 3){
         console.log("found 3");
        //do something here.
         }
}

Upvotes: 2

Michel
Michel

Reputation: 28339

This is more a js problem than an angular one. If you are using a library like lodash this is pretty straightforward :

_.findWhere(array, {'id': 3})

In plain javascript this is not much complicated. Here is an EcmaScript 5 solution, that makes use of the function some :

array.some(function(elem) {
    return elem.id === 3;
});

Upvotes: 2

Shimon Brandsdorfer
Shimon Brandsdorfer

Reputation: 1723

you can do it with plain JavaScript:

array.find(function(element){
    if(element.id == 3) return true;
})

Upvotes: 0

Daniel Beck
Daniel Beck

Reputation: 21505

You don't need lodash, even. Native javascript:

(array.filter(function(a) {return a.id === 3})

will return an array containing only the element whose id is 3 if there is one, or an empty array if not.

Upvotes: 0

Related Questions