Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I need to find out, is there in array of objects object with the certain key:value For example if I need the key 'id' to be unique:

arr=[
     {id:1,  attr1:'435',attr2:'sdg'},
     {id:2,  attr3:'4x35',attr2:'sdg'}
    ];

a={id:1,attr2:'nnsklnf'};
b={id:3,attr3:'kldfmlkdblng'};

function isHaveSimilar(_a,_array){
 // ... ???
}

isHaveSimilar(a,arr); // true
isHaveSimilar(b,arr); // false

Maybe there is some easier way than the rude checking of the each element? Thx)

share|improve this question
No, I believe the "rude check" is the way. – lanzz May 30 '12 at 11:24
up vote 0 down vote accepted
function hasSimilar(needle, haystack) {
  for (item in haystack) {
    if (haystack[item].id == needle.id) {
      return true;
    }
  }
  return false;
}

hasSimilar(a, arr); // true
hasSimilar(b, arr); // false
share|improve this answer
Thank you. I don't see another way also. Thought maybe there is something that allowed to solve it in one line in jQuery or maybe some function in JSON, it maybe useless but just curious :] – 2oppin May 31 '12 at 7:53

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.