Book Image

Lo-Dash Essentials

By : Adam Boduch
Book Image

Lo-Dash Essentials

By: Adam Boduch

Overview of this book

Table of Contents (15 chapters)
Lo-Dash Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Transforming objects


Sometimes, we're implementing a feature and the given object we're working with just doesn't fit the bill—you need to transform it into a structure that's better suited for our needs. There are a handful of functions that are shipped with Lo-Dash to help us do this. We can create an array of arrays out of objects, we can pick and choose which object properties we want to work with, and we can turn an object inside out by inverting its keys and values.

Using pairs

The pairs() function accepts an object argument and generates an array of which each element is itself an array, which contains the key and the value. This structure can be a lot more convenient to work with under some circumstances. An example of this is shown in the following code:

function format(label, value) {
    return label + ': ' + value;    
}   
var object = { 
    first: 'Katherine',
    last: 'Bailey',
    age: 33
}, result = '';
 
_.forEach(_.pairs(object), function(pair) {
    result += format.apply...