将对象数组映射到按对象键js immutable分组的映射中

时间:2016-10-04 13:43:09

标签: javascript object reduce immutable.js seamless-immutable

我想映射一个对象数组,以输出按特定对象键分组的不可变映射。

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 as:

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] :(

2 个答案:

答案 0 :(得分:1)

您可以使用.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>

答案 1 :(得分:0)

您可以使用普通的Javascript对项目进行分组。

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; }