Created
October 30, 2014 04:24
-
-
Save Centril/0a7e5c211193a1aee1fd to your computer and use it in GitHub Desktop.
lodash: _.objectMap
This file contains 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
/** | |
* Creates an object where each property is composed from | |
* an element of keys (key) and the value from callback(key). | |
* | |
* @param {array} keys The array of keys. | |
* @param {function} [callback=_.identity] The callback(key) that returns the object:s values. | |
* @return {object} Returns an object composed of the given keys and callback(key) for values. | |
*/ | |
_.objectMap = function(keys, callback) { | |
callback = callback || _.identity; | |
var object = {}; | |
for(var index = 0, len = keys.length; index < len; ++index) { | |
var key = keys[index]; | |
object[key] = callback(key); | |
} | |
return object; | |
}; | |
// In other words: | |
_.objectMap = function(array, func) { | |
return _.object(array, _.map(array, func)); | |
}; | |
// An example | |
var config = _.objectMap(['package', 'colors', 'external', 'languages'], function(file) { | |
return grunt.file.readJSON(file + '.json'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment