0

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)

2oppin
  • 1,941
  • 20
  • 33

1 Answers1

0
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
Fczbkk
  • 1,477
  • 1
  • 11
  • 23
  • 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 07:53