Last active
June 7, 2017 19:36
-
-
Save olizilla/7e44179ea0467588dbaf7dc70d574516 to your computer and use it in GitHub Desktop.
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
/** | |
* Convert cols and rows into an array of objects. | |
* Will return array of objects mapping cols to row values. | |
* | |
* Repeated cols are mapped to array values. | |
* | |
* @param {Array} cols The keys | |
* @param {Array} rows the array of arrays of values | |
* @return {Array} The rows as objects | |
* @example | |
* objectify( | |
* ['name', 'email', 'email'], | |
* [ | |
* ['Derp', '[email protected]', '[email protected]'] | |
* ] | |
* ) | |
* // => [{ name: 'Derp', email: ['[email protected]', '[email protected]'] }] | |
*/ | |
function objectify (cols, rows) { | |
// Create a map of key to fn(memo, key, val) | |
const colMap = cols.reduce((colMap, key) => { | |
if (colMap[key]) { | |
colMap[key] = keyToArray | |
} else { | |
colMap[key] = keyToVal | |
} | |
return colMap | |
}, {}) | |
return rows.map((row) => { | |
// colMap[key] is a fn(memo, key, val) | |
return cols.reduce((memo, key, i) => colMap[key](memo, key, row[i]), {}) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment