2016-10-04 330 views
4

我想映射對象數組以輸出由特定對象關鍵字分組的不可變映射。將對象數組映射到按對象關鍵字分組的映射js不可變

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或無縫不變的最有效的方法?

目前即時通訊使用減少爲:

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

回答

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

+0

調用'r.byTime [a.time]'三次似乎過高。 –

+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>