Skip to content

Instantly share code, notes, and snippets.

@rcdilorenzo
Created November 16, 2018 01:11
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 rcdilorenzo/f843c26b22a6629b3b277b7da4e33479 to your computer and use it in GitHub Desktop.
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
// ========
// 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