diff --git a/snippets/mapKeys.md b/snippets/mapKeys.md new file mode 100644 index 000000000..2b50ddd84 --- /dev/null +++ b/snippets/mapKeys.md @@ -0,0 +1,15 @@ +### mapKeys + +Creates an object with keys generated by running the provided function for each key and the same values as the provided object. + +Use `Object.keys(obj)` to iterate over the object's keys. +Use `Array.reduce()` to create a new object with the same values and mapped keys using `fn`. + +```js +const mapKeys = (obj, fn) => + Object.keys(obj).reduce((acc,k) => {acc[fn(obj[k], k, obj)] = obj[k]; return acc;},{}); +``` + +```js +mapKeys({ 'a': 1, 'b': 2 }, (val, key) => key + val); // { a1: 1, b2: 2 } +``` diff --git a/snippets/mapValues.md b/snippets/mapValues.md new file mode 100644 index 000000000..79dbc7415 --- /dev/null +++ b/snippets/mapValues.md @@ -0,0 +1,19 @@ +### mapValues + +Creates an object with the same keys as the provided object and values generated by running the provided function for each value. + +Use `Object.keys(obj)` to iterate over the object's keys. +Use `Array.reduce()` to create a new object with the same keys and mapped values using `fn`. + +```js +const mapValues = (obj, fn) => + Object.keys(obj).reduce((acc,k) => {acc[k] = fn(obj[k], k, obj); return acc;},{}); +``` + +```js +const users = { + 'fred': { 'user': 'fred', 'age': 40 }, + 'pebbles': { 'user': 'pebbles', 'age': 1 } +}; +mapValues(users, u => u.age); // { fred: 40, pebbles: 1 } +``` diff --git a/tag_database b/tag_database index 73d0a8310..353f5fda5 100644 --- a/tag_database +++ b/tag_database @@ -103,7 +103,9 @@ lcm:math,recursion longestItem:array,string,utility lowercaseKeys:object luhnCheck:math,utility +mapKeys:object,function mapObject:array,object +mapValues:object,function mask:string,utility,regexp maxBy:math,array,function maxN:array,math