Created
November 16, 2018 01:11
-
-
Save rcdilorenzo/f843c26b22a6629b3b277b7da4e33479 to your computer and use it in GitHub Desktop.
Transpose list of objects to an object with each property as a list of the values
This file contains hidden or 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
// ======== | |
// Usage | |
// ======== | |
// > const { transposeObjects } = require('./utils'); | |
// undefined | |
// > transposeObjects([ | |
// ... { key1: 'object1key1', key2: 'object1key2' }, | |
// ... { key1: 'object2key1', key2: 'object2key2' } | |
// ... ]) | |
// { key1: [ 'object1key1', 'object2key1' ], | |
// key2: [ 'object1key2', 'object2key2' ] } | |
const R = require('ramda'); | |
const lensPropWithDefault = R.curry((defaultValue, key) => { | |
return R.lens(R.propOr(defaultValue, key), R.assoc(key)); | |
}); | |
const transposeObjects = (objects) => { | |
const appendProperty = R.curry((object, acc, key) => { | |
return R.over( | |
lensPropWithDefault([], key), | |
R.append(R.prop(key, object)), | |
acc | |
); | |
}); | |
const appendProperties = (acc, object) => { | |
return R.reduce(appendProperty(object), acc, R.keys(object)); | |
}; | |
return R.reduce(appendProperties, {}, objects); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment