Skip to content

Instantly share code, notes, and snippets.

@olizilla

olizilla/objectify.js

Last active Jun 7, 2017
Embed
What would you like to do?
/**
* 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
You can’t perform that action at this time.