2017-08-08 64 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