Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@olizilla
Last active June 7, 2017 19:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olizilla/7e44179ea0467588dbaf7dc70d574516 to your computer and use it in GitHub Desktop.
Save olizilla/7e44179ea0467588dbaf7dc70d574516 to your computer and use it in GitHub Desktop.
/**
* 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', '1@yes.no', '2@butt.systems']
* ]
* )
* // => [{ name: 'Derp', email: ['1@yes.no', '2@butt.systems'] }]
*/
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