Book Image

Learning Underscore.js

By : Alexandru Vasile Pop
Book Image

Learning Underscore.js

By: Alexandru Vasile Pop

Overview of this book

Table of Contents (14 chapters)
Learning Underscore.js
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Objects


Underscore has a series of dedicated functions targeting objects, which extends the features provided for collections.

Underscore keys

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 [];
 ...