Last active
December 30, 2015 23:31
-
-
Save choonkending/f81c657a36987d922936 to your computer and use it in GitHub Desktop.
Mapping an array to an object
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
/* | |
* Given an array of pairs | |
* such as this | |
* `['a-b','b-c']` | |
* | |
* and we wish to convert to | |
* `{ | |
* a: b, | |
* b: c | |
* }` | |
*/ | |
/* | |
* @param {Array} pairs such as ['a-b', 'b-c'] | |
* @param {String} a delimiter that it used to split each item in the array | |
*/ | |
export default function createMapFromPairs(pairs, pairDelimiter) { | |
return pairs.reduce(function (result, currentPair) { | |
var keyValueArray = currentPair.split(pairDelimiter); | |
result[keyValueArray[0]] = keyValueArray[1]; | |
return result; | |
}, {}); | |
} | |
/* | |
* Sample usage: | |
* var array = ['a-b', 'b-c']; | |
* var pairDelimiter = '-'; | |
* createMapFromPairs(array, pairDelimiter); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment