Skip to content

Instantly share code, notes, and snippets.

@choonkending
Last active December 30, 2015 23:31
Show Gist options
  • Save choonkending/f81c657a36987d922936 to your computer and use it in GitHub Desktop.
Save choonkending/f81c657a36987d922936 to your computer and use it in GitHub Desktop.
Mapping an array to an object
/*
* 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