簡體   English   中英

將對象數組映射到按對象鍵分組的映射中 js 不可變

[英]map array of objects into map grouped by object key js 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 或無縫不可變的最有效方法是什么?

目前我使用 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> 

您可以使用普通的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; } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM