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?
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,
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;
});
you can do it with plain JavaScript:
array.find(function(element){
if(element.id == 3) return true;
})
find is an ECMAScript 2015 method, and because of that it has very poor browser support as of now.
idproperty equals3,afterid:3? updated my answer.