1

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)
1
  • 1
    What you have is not an array. It's a javascript object with many properties. Arrays are denoted with square brackets. Don't mistake those two different notions. Commented Oct 1, 2010 at 19:10

3 Answers 3

2
"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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

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;
0
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

​

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.