Last active
July 24, 2016 09:14
-
-
Save irvinlim/fbc42287c44ffed599602219a23c2a7d to your computer and use it in GitHub Desktop.
Similar to Array.prototype.map, these methods run a function on every object property or object key.
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
// Inspired from http://stackoverflow.com/a/14810722/2037090 | |
/** | |
* Maps object keys using a given function. | |
* @param {Object} obj Target object | |
* @param {Function} fn Mapping function that takes in an object key, and returns a new object key. | |
* Method signature: | |
* function(key: string) => newKey: string | |
* @return {Object} Newly constructed object with mapped keys. Original object is not modified. | |
*/ | |
const map_obj_keys = function(obj, fn) { | |
return Object.keys(obj).reduce(function(accum, curr) { | |
accum[fn(curr)] = obj[curr]; | |
return accum; | |
}, {}); | |
}; | |
/** | |
* Maps object properties using a given function. | |
* @param {Object} obj Target object | |
* @param {Function} fn Mapping function that takes in an object property value, and returns a new value to be assigned. | |
* Method signature: | |
* function(value, key: string) => newValue | |
* @return {Object} Newly constructed object with mapped properties. Original object is not modified. | |
*/ | |
const map_obj = function(obj, fn) { | |
return Object.keys(obj).reduce(function(accum, curr) { | |
accum[curr] = fn(obj[curr], curr); | |
return accum; | |
}, {}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment