Lodash keyBy

by findango

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
<script>
function stringify(value) {
	  return typeof value === 'object' ?
  	    JSON.stringify(value, null, 2) :
    		value;
}

function log() {
    var args = Array.prototype.slice.call(arguments, 0);
    document.getElementById('output').innerHTML += args.map(stringify).join(" ") + "\n";
}
</script>

<pre id="output"></pre>

JavaScript

const list = [
	{ name: 'foo', amount: 1, other: 17, type: 'A' },
  { name: 'bar', amount: 2, other: 21, type: 'B' },
  { name: 'baz', amount: 3, other: 36, type: 'A' },
  { name: 'baz', amount: 3, other: 36, type: '' },
  { name: 'baz', amount: 3, other: 36 },
];

/* log('list', list);
log('keyed', _.keyBy(list, 'name'));
log('chained', _(list).keyBy('name').mapValues(obj => obj.amount));
log('nested', _.mapValues(_.keyBy(list, 'name'), 'amount'));
 */
log('groupBy into array', _.groupBy(list, 'type'));