Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

map array of objects into map grouped by object key js immutable

i want to map an array of object to output Immutable Map that is grouped by specific object key.

array looks like
[
 {id:1, time:19072016},
 {id:2, time:19072016},
 {id:3, time:19072015},
]
output im seeking is
[
 byId: {
  1:{id:1, time:19072016},
  2:{id:2, time:19072016},
  3:{id:3, time:19072015},
 },
 byTime: {
  19072016:[1,2],
  19072015:[3],
 }
]

what is most effective way to do it using immutablejs or seamless-immutable ?

currently im using reduce as :

array.reduce( (final,row) =>final.setIn(['byId',row.id],row) ,
              Immutable.Map({byId:{},byTime:{}});

this output byIds as i want it, but problem with byTime is that i need to merge not overwrite.

i tried with seamless-immutable i did:

Seamless(arr).toObject(i=>[i.id,i]) //this will return byId as i want it
Seamless(arr).toObject(i=>[i.time,[i.id]]) //this will not merge [1,2] :(
like image 580
Zalaboza Avatar asked Oct 18 '22 00:10

Zalaboza


1 Answers

You can get what you want by using .groupBy() and .map().

const data = Immutable.fromJS([
  {id:1, time:19072016},
  {id:2, time:19072016},
  {id:3, time:19072015},
]);

const byId = data
  .groupBy(item => item.get('id'))
  .map(items => items.first());
console.log(byId);

const byTime = data
  .groupBy(item => item.get('time'))
  .map(items => items.map(item => item.get('id')));
console.log(byTime);
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.2/immutable.js"></script>
like image 97
Simon Baumgardt-Wellander Avatar answered Oct 21 '22 01:10

Simon Baumgardt-Wellander