user5671335 user5671335 - 1 month ago 13
Javascript Question

Lodash chain and groupBy

Have an array

var list = [
{id: 1, name: 'name1', type: 'type1'},
{id: 2, name: 'name2', type: 'type1'},
{id: 3, name: 'name3', type: 'type1'},
{id: 4, name: 'name4', type: 'type2'},
{id: 5, name: 'name5', type: 'type3'},
{id: 6, name: 'name6', type: 'type3'}
];


How do I get the following:

var obj = {
type1: {
1: {id: 1, name: 'name1', type: 'type1'},
2: {id: 2, name: 'name2', type: 'type1'},
3: {id: 3, name: 'name3', type: 'type1'}
},
type2: {
4: {id: 4, name: 'name4', type: 'type2'}
},
type3: {
5: {id: 5, name: 'name5', type: 'type3'},
6: {id: 6, name: 'name6', type: 'type3'}
}
};


I tried:

_.chain(list).groupBy('type').value();


But it turned out only to break the array of the type.

Answer

You can use reduce() to do this in pure js.

var list = [
    {id: 1, name: 'name1', type: 'type1'},
    {id: 2, name: 'name2', type: 'type1'},
    {id: 3, name: 'name3', type: 'type1'},
    {id: 4, name: 'name4', type: 'type2'},
    {id: 5, name: 'name5', type: 'type3'},
    {id: 6, name: 'name6', type: 'type3'}
];

var result = list.reduce(function(r, e, i) {
  if(!r[e.type]) r[e.type] = {}
  r[e.type][i+1] = e;
  return r;
}, {})

console.log(result)