将 Ramda indexBy 与可变索引一起使用

Use Ramda indexBy with variable index

我需要转换一些 JSON 数据,而 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' } }

如果我对你的问题的理解正确,你希望 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 沿原型链上升,顺序 有保证。