Copy Specific Properties
22 August 2014
While working with some results from an API call, I needed to copy several (but not all) of their properties onto model objects I would use for application state. Most copy or clone functions grab every property from the source object but I wanted to just list a few.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function copy( prop ) { | |
var receiver, target; | |
function bindFrom( obj ) { | |
target = obj; | |
return copyProp(); | |
} | |
function bindTo( obj ) { | |
receiver = obj; | |
return copyProp(); | |
} | |
function copyProp() { | |
if ( target && receiver ) { | |
if ( prop in target ) { | |
receiver[prop] = target[prop]; | |
} | |
return receiver; | |
} | |
return { | |
from: bindFrom, | |
to: bindTo | |
}; | |
} | |
return copyProp(); | |
}; |
I like code that tells a story. It’s hard for other developers (or future me) to get confused:
copy( 'some_property' ).from( objectA ).to( objectB );
When I use it to collect specific property values from API results, I map over a pre-determined list, like this:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var result = {id:1, foo: 'bar', baz: null}; | |
var myObj = ['foo', 'baz'] | |
.map( copy ) | |
.reduce( function ( obj, copyProp ) { | |
return copyProp.from( result ).to( obj ); | |
}, {} ); | |
//=> {foo: "bar", baz: null} |