Starkers
Starkers

Reputation: 10551

Is there an $.inArray function for objects / hashes?

Something like this:

object = { 'one' : 1, 'two' : 2 }
$.inObject(object, 'one') // returns true
$.inObject(object, 'three') // returns false

It would only search the keys.

Upvotes: 2

Views: 114

Answers (3)

Steven de Salas
Steven de Salas

Reputation: 21497

Yep, the in keyword. No need to use jQuery:

object = { 'one' : 1, 'two' : 2 };
alert('one' in object); // true
alert('three' in object); // false

You can also use object.hasOwnProperty('blah') which is more reliable. Douglas Crockford prefers this approach, you will find JSLint complaining about this occassionally. I prefer the in notation as its easier to read.

Upvotes: 5

jfriend00
jfriend00

Reputation: 708036

The safest way to do this is using .hasOwnProperty():

obj = { 'one' : 1, 'two' : 2 };
obj.hasOwnProperty('one') // returns true
obj.hasOwnProperty('three') // returns false

You can also use the in operator as others have suggested like this:

obj = { 'one' : 1, 'two' : 2 };
console.log('one' in obj)   // true
console.log('three' in obj) // false

But, the in operator can be confused by any properties on the prototype of the object that might have been added to Object by some library or other code so hasOwnProperty() is generally considered the safer option for detecting things you added to the actual object yourself. In otherwords, if anyone added an method or property to the Object prototype, it would get picked up by the in operator, but not by .hasOwnProperty() which only checks the actual object itself, not any inherited properties.


FYI, this may be overkill for what you need for your particular use, but there's an implementation of a Set object and a ValueSet object that uses this type of logic and offers lots of typical Set operations here: Mimicking sets in JavaScript?. The code is all available for the Set object too so you can see how it all works if you want to educate yourself further.

Upvotes: 8

akirk
akirk

Reputation: 6857

You could use typeof:

function inObject(obj, key) {
    return typeof obj[key] != "undefined";
}

Upvotes: 0

Related Questions