Shpigford
Shpigford

Reputation: 25328

How to find item in array using jQuery?

So I have this array:

var statuses = { New:1, Addressed:2, Rejected:3, Recovered:4, Billed:5, Completed:6 };

And I'd like to basically search the array for the "Rejected" key and have it return the value, so I can then go back/forth in the array as needed.

I've tried this, but it always fails with a "-1" saying it can't find it.

jQuery.inArray("Rejected", statuses)

Upvotes: 1

Views: 7667

Answers (3)

andres descalzo
andres descalzo

Reputation: 14967

var statuses = { New:1, Addressed:2, Rejected:3, Recovered:4, Billed:5, Completed:6 };

​$.inJsonObject = function(ind, obj)​​​ {

    return (typeof obj[ind] != 'undefined');

}​;

$.inJsonObject('Rejected', statuses); // true / false

​

Upvotes: 0

Matt
Matt

Reputation: 75307

That's not an array, that's an object.

It's a lot easier:

if (statuses.hasOwnProperty("Rejected")) {
  // It has it
  var valueOfRejected = statuses.Rejected

  // valueOfRejected now equals 3
} else {
  // It doesn't
}

You can safely retrieve the Rejected key, even if it doesn't exist in the Object without throwing an error; the retrieved value will just equal undefined.

Upvotes: 2

Skilldrick
Skilldrick

Reputation: 70819

"Rejected" in statuses;

No need for jQuery.

If you want the value, do:

statuses["Rejected"];

This will return undefined if "Rejected" is not in the object.

As the others have said, literals of the form {blah: value, blah2: value} represent objects, and those like [value1, value2, value2] represent arrays.

Upvotes: 2

Related Questions