tags:

views:

68

answers:

3

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)
+2  A: 
"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.

Skilldrick
+2  A: 

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.

Matt
If a property doesn't exist on an object, and you try to access it, there's no error thrown, it will simply produce `undefined` e.g. `({}).iDontExist === undefined;`
CMS
A: 
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

​
andres descalzo