我想映射一个对象数组来输出按特定对象键分组的不可变映射.
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],
}
]
使用immutablejs或seamless-immutable做什么最有效的方法是什么?
目前我正在使用reduce作为:
array.reduce( (final,row) =>final.setIn(['byId',row.id],row) ,
Immutable.Map({byId:{},byTime:{}});
这个输出byIds就像我想要的那样,但是byTime的问题是我需要合并而不是覆盖.
我试过无缝不可变我做了:
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] :(
最佳答案 您可以使用
.groupBy()
和
.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>