7

I have a JSON array that looks like this:

['Monkey','Cheetah','Elephant','Lizard','Spider']

I also have a text input. I want to test whether the value of the input upon 'blur' is also in the array and if it is do something.

Knowing a bit of python I tried something like this:

var existing_animals = ['Monkey','Cheetah','Elephant','Lizard','Spider']
$('input').blur(function() {
  user_animal = $(this).val()
  if (user_animal in existing_animals) {
    alert('Animal already exists!')
  }
});

So, how rookie is my mistake?

chrism
  • 2,905
  • 8
  • 37
  • 40
  • Sorry about the typo in the heading and in the example - should say 'user_animal in existing_animals' – chrism May 14 '10 at 14:05
  • The code you posted checks for existing_animals.Monkey (or, equivalently, existing_animals['Monkey']). The array stores it like: existing_animals[0] = 'Monkey'; it's not associative. I think korchev's solution is the best one (using $.inArray), but you could also make it associative as Matt suggested. – RMorrisey May 14 '10 at 14:23

4 Answers4

6

The in operator checks if a key is present in a dictionary (object). It however does now work for arrays. The right approach is to use jQuery.inArray:

if ($.inArray(user_animal, existing) > -1) {
    alert('Animal already exists!')
}
Atanas Korchev
  • 30,562
  • 8
  • 59
  • 93
  • I knew I use jQuery for a reason, while the other answers may be right, this is simple enough even for me, thanks – chrism May 14 '10 at 14:20
4

in is for checking if an object includes the attribute, where-as you're using an array.

If you want to use your in, you can do:

var existing_animals = {
  "Monkey":1,
  "Cheetah":1
};

etc, then all will be fine using in, however, it would be better to continue using your Array, and simply loop over it.

$('input').blur(function() {
  user_animal = $(this).val()

  for (var i=0;i<existing_animals.length;i++) {
     if (existing_animals[i] == user_animal) {
        alert("Animal exists");

        break;
     };
  };
});

The ECMA 5th edition introduces an indexOf method for Arrays, so it should be as easy as doing:

if (existing_animals.indexOf(user_animal) != -1) {
   alert("Animal exists");
};

However, IE doesn't support this; you can implement it yourself though.

Matt
  • 74,352
  • 26
  • 153
  • 180
0

If you want to use the "in" keyword in JS, this might be helpful: Reduce multiple ORs in IF statement in Javascript

Community
  • 1
  • 1
Edgar
  • 4,348
  • 4
  • 40
  • 59
0

I believe you might find your answer in this article.

Since the JSON evaluates to an array, you should be looking at the indexOf function. Not sure why you mentioned python here..

Community
  • 1
  • 1
Jeriko
  • 6,547
  • 4
  • 28
  • 40