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] :(
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>
You could use plain Javascript for grouping the items.
var data = [{ id: 1, time: 19072016 }, { id: 2, time: 19072016 }, { id: 3, time: 19072015 }, ], result = data.reduce(function (r, a) { r.byId[a.id] = a; r.byTime[a.time] = r.byTime[a.time] || []; r.byTime[a.time].push(a.id); return r; }, { byId: {}, byTime: {} }); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
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.