简体   繁体   中英

Can I use Lodash to “collapse” an array of objects?

Currently my array looks something like

[{index: 1, value: 'A'},
 {index: 1, value: 'B'},
 {index: 2, value: 'C'},
 {index: 5, value: 'D'}]

I'm trying to turn that into an object like

{
  1: ['A', 'B'],
  2: ['C'],
  5: ['D']
}

Currently I'm just sorting the array, then running a convoluted for-loop

You can use .groupBy + .mapValues + .map

 var data = [{ index: 1, value: 'A' }, { index: 1, value: 'B' }, { index: 2, value: 'C' }, { index: 5, value: 'D' }]; var result = _(data) .groupBy('index') .mapValues(function (el) { return _.map(el, 'value'); }) .value(); console.log(result); 
 <script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.0.0/lodash.js"></script> 

also you can avoid several operation and can use only .reduce like this

 var data = [{ index: 1, value: 'A' }, { index: 1, value: 'B' }, { index: 2, value: 'C' }, { index: 5, value: 'D' }]; var result = data.reduce(function (prev, current) { if (typeof (prev[current.index]) === 'undefined') { prev[current.index] = []; } return prev[current.index].push(current.value) && prev; }, {}); console.log(result); 
 <script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script> 

@Alexander's answer is probably a lot more clear than this, but I'm addicted to partials and allergic to anonymous functions, so here's a version with partials!

var data = [
    {index: 1, value: 'A'},
    {index: 1, value: 'B'},
    {index: 2, value: 'C'},
    {index: 5, value: 'D'}
];

// define a couple of resuable functions for these objects
var getValueProp = _.partial(_.get, _, 'value');
var mapToValueProp = _.partial(_.map, _, getValueProp);

// get the answer!
var result = _(data)
    .groupBy('index')
    .mapValues(mapToValueProp)
    .value();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM