2017-08-08 66 views
0

我需要轉換一些JSON數據,而Ramda的indexBy只是完成我想要的。下面的代碼適用於單個對象:使用Ramda indexBy與變量索引

const operativeIndex = R.pipe(R.head, R.keysIn, 
    R.intersection(['Weight', 'Height', 'Month', 'Week']), R.head); 
const reIndex = R.indexBy(R.prop(operativeIndex(testObject)), testObject); 

但是通過我重新索引功能映射對象的數組,我相信我需要重寫reIndex所以它只需要的testObject單次注射。

我該怎麼做?


以幫助觀察任務:當前代碼變換testObject從這樣的陣列,其將具有4個允許指標之一:

[{ Height: '45', 
     L: '-0.3521', 
     M: '2.441', 
     S: '0.09182'}, 
{ Height: '45.5', 
     L: '-0.3521', 
     M: '2.5244', 
     S: '0.09153'}] 

成這樣的對象:

{ '45': 
    { Height: '45', 
    L: '-0.3521', 
    M: '2.441', 
    S: '0.09182' }, 
    '45.5': 
    { Height: '45.5', 
    L: '-0.3521', 
    M: '2.5244', 
    S: '0.09153' } } 

回答

1

如果我正確理解你的問題,你想reIndex是一個函數,它接受一個對象列表併產生一個對象索引。

如果是的話,你可以這樣

const operativeIndex = R.pipe(
    R.keysIn, 
    R.intersection(['Weight', 'Height', 'Month', 'Week']), 
    R.head 
) 

const reIndex = R.indexBy(R.chain(R.prop, operativeIndex)) 

做那麼你可以做reIndex(list)Demo

順便提一下,請記住,keysIn上升原型鏈和訂單是保證。

+0

是的,這正是我所需要的。重寫'reIndex'後,我現在可以使用'R.map(reIndex,list)'並使用一個函數重新索引上面的'testObject'等許多對象。 – ed94133