Underscore has a series of dedicated functions targeting objects, which extends the features provided for collections.
We will revisit the propertyFormatter
related examples to showcase some of the object-related features, and we will start with the function _.keys(object)
. This function will extract an array containing the names of all enumerable properties from the object
parameter. It ignores any properties that are inherited, and if you want to include those as well you need to use the _.allKeys(object)
function instead.
Going back to the original propertyFormatter.extractPropertiesForDisplayAsArray()
function introduced in Chapter 2, Using Underscore.js with Collections, we can now change it to use _.keys(object)
to ensure we only process objects that have at least one valid property:
extractPropertiesForDisplayAsArray: function(source, ignoreId) {
if (!source || (!ignoreId && source.id !== +source.id) || _.keys(source).length === 0) {
return [];
...