Javascript Function for Finding an Object’s Properties
May 19, 2008
This function makes use of Douglas Crockford‘s functions available from his Remedial Javascript page. If you haven’t read his series of articles on Javascript, you’re missing out. Also, check out the Yahoo User Interface team’s website and the YUI blog for more Javascript info and tips.
Crockford’s isEmpty function:
function isEmpty(o) {
var i, v;
if (typeOf(o) === 'object') {
for (i in o) {
v = o[i];
if (v !== undefined && typeOf(v) !== 'function') {
return false;
}
}
}
return true;
}
As a question to the readers, how should the isEmpty function treat object properties that are undefined or functions? Currently, the function ignores undefined properties and functions. Should it count them as properties?
My getProperties function looks much like the isEmpty function and uses the same method for accessing an object’s properties. Rather than return true or false based on the existence of properties, this function returns an array of all of the property names for the given object. A trivial modification of the isEmpty function, but useful none the less.
function getProperties(obj) {
var i, v;
var count = 0;
var props = [];
if (typeof(obj) === 'object') {
for (i in obj) {
v = obj[i];
if (v !== undefined && typeof(v) !== 'function') {
props[count] = i;
count++;
}
}
}
return props;
};
June 3, 2008 at 3:57 am
Very interesting, thanks. Javascript could really do with a native function that lets you perform an Object.length in the same way as you can an array.length.
Just as an aside, in the getProperties function, couldn’t you get rid of the count variable and just say:
props[props.length] = i;
?
June 3, 2008 at 7:46 am
Thanks for the comments!
That’s an interesting idea using props.length as the array index. Wouldn’t that result in every property being assigned to the same index of props[props.length] ?
March 20, 2009 at 6:19 pm
Nice one. It really helped me out.