Join the Stack Overflow Community
Stack Overflow is a community of 6.5 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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?

share|improve this question
    
I'd say you should loop through the array and see if the id property equals 3 – Jan Jul 6 '15 at 22:27
    
What aspect of the problem do you have trouble with? Do you understand how to loop over an array? – meriton Jul 6 '15 at 22:28
    
@teddybear123 aren't u missing a , after id:3? updated my answer. – Sudhansu Choudhary Jul 7 '15 at 12:37

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,

share|improve this answer
    
great answer..work perfect..thnks – The developer Sep 8 at 5:43

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;
});
share|improve this answer

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.
         }
}
share|improve this answer

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.

share|improve this answer

you can do it with plain JavaScript:

array.find(function(element){
    if(element.id == 3) return true;
})
share|improve this answer
2  
find is an ECMAScript 2015 method, and because of that it has very poor browser support as of now. – Michael P. Bazos Jul 6 '15 at 22:55

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.