Monday, April 28, 2014

Lodash: Picking Object Properties to Extend

The extend() function is one of those Lodash tools that's so indispensable, you wonder how the core JavaScript language doesn't have something similar built-in. There's another Lodash function I'm developing similar feelings toward — pick(). This function operates on objects, and returns a new object, containing only properties "picked" from the source object. Something like this comes in handy when extending objects.

Consider the following code that uses extend() to extend the properties of the myData object.

var myData = { key1: 'val1' };

_.extend( myData, {
    key1: 'different value',
    key2: 'val2',
    key3: 'val3'
});

Since key1 already had a defined value prior to calling extend, the resulting object keeps the "val1" value, and not "different value". It'll also have all the other properties of the source object, in this case, key2 and key3. But what if we don't care about key3 and it's value. In fact, there could be dozens of properties I don't care about — especially working with objects defined by someone else with a different purpose in mind. Then we would use something like pick().

var myData = { key1: 'val1' };

_.extend( myData, _.pick({
    key1: 'different value',
    key2: 'val2',
    key3: 'val3'
}, [ 'key1', 'key2' ] );

Here we're using pick() to tell extend() that we only care about the key1 and key2 properties. What's nice about this code is that I can just leave it alone, and let other developers add new properties to it — I'll never see them.