Count the Number of Object keys/properties in Node.js

When using the excellent formidable library to handle file uploads, I needed to get a count of the number of files unloaded in a multi-part form. Javascript arrays have a .length property that you can use, but objects do not. I instinctively typed:

1
files.length

Which returned undefined. So if there is no length property present, an easy way to count the number of keys or properties of an object in ES5-compliant javascript environments like Node.js is to use the Object prototype directly:

1
Object.keys(files).length

A little more typing, but it is fast, efficient, and most importantly: already built-in.

Tags:
Hire Me

Have a problem you need help solving?
I'm available for freelance work. (and I love solving hard problems)

Comments are closed.

All content copyright © 2013 Vance Lucas | Powered by WordPress | Entries (RSS) | Comments (RSS)