JavaScript LogoWhen you need to get all of the names of an object’s properties as an array of strings, the Object.getOwnPropertyNames method is an excellent tool

In the article: “The JavaScript for…in statement – enumerating object properties,” I discussed the for-in statement as the “go-to” tool for object enumeration. I’m a big fan of that feature and feel it is worth its weight in gold. But I’d be remiss if I did not mention Object.getOwnPropertyNames.

The getOwnPropertyNames method of the “Object” object differs from the for-in statement in two ways: It returns an array, and the elements of that array are strings. These strings are the property names of the specified object.

Example # 1 A

Example # 1 B

In Example # 1 A, we create the object: “userObject”. Then using the Object.getOwnPropertyNames method, we inspect it. Example # 1B accomplishes the same thing, but the results are significantly different because we inspect the window object, and there are literally hundreds of properties. In each case though, the return value of the Object.getOwnPropertyNames method is an array. The array elements are strings that contain the names of each property contained in that object. But what if we want to get the value of each property?

Example # 2

In Example # 2, we use the jQuery.each method to enumerate the elements of the array returned by the Object.getOwnPropertyNames method. Inside the callback, we output not only the name of the property, but the value of that property. The key here is that we use the following syntax: userObject[val]. Since we know the name of the property, we can use bracket notation to get its value (e.g. object[propertyName] ).

Summary

The Object.getOwnPropertyNames method may not always be the right tool for the job. Some may say that the for-in statement is more than sufficient for object enumeration and, often, that may very well be the case. But if you ever need to get all of the names of an object’s properties as an array of strings, the Object.getOwnPropertyNames method is an excellent tool.

Helpful Links for Object.getOwnPropertyNames

http://mdn.beonex.com/en/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames.html