Amazon.ca Widgets

How to know if a javascript object contains a property

You want to know if your javascript object contains a certain attribute. But, you tried some methods, and, because of the “undefined” value, it’s hard to differ from an undefined value, from an undefined “property”.

Let’s look at that simple example:

var obj = {
	key1: "value1",
	key2: "value2",
	key3: undefined
};

You want to know if obj contains “key4” property.
First, you try with “typeof”. But, for key3 and key 4, you get the same result:

typeof obj.key3
	"undefined"
typeof obj.key4
	"undefined"

So, what about property value?

obj.key3
	undefined
obj.key4
	undefined

The method I use is hidden in the very underused “Object” object.

Object.keys(xxx) returns an array of all properties of your object, as string.
So, you can do an indexOf that property name to know if it is contained in its definition.

Object.keys(obj).indexOf("key3")
	2
Object.keys(obj).indexOf("key4")
	-1

So, if you want to know if your property “exists” in your object:

function isDefined(obj, prop){
	return Object.keys(obj).indexOf(prop) > -1;
}

Another better alternative is to use the native hasOwnProperty inherited from Object.

The previous sample can also be:

obj.hasOwnProperty("key3") -> true
obj.hasOwnProperty("key4") -> false

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: