如何使用 Ramda 将对象数组映射到单个对象

How to map an array of objects to a single object using Ramda

我需要转这个:

let arr = [{ id: 1, name: 'rod'} , { id: 2, name: 'hey' }]

进入:

mapO = { 1: 'rod', 2: 'hey' }

那是我试过的:

let mapIdName = (o) => {
  let ret = {};
  ret[o["id"]] = o['name'];
  return ret;
}

let mergeIdNames = R.mergeAll(R.map(mapIdName));

mergeIdNames(o)

错误:

mergeIdNames is not a function

您可以使用 R.indexBy:

> R.map(R.prop('name'), R.indexBy(R.prop('id'), [{id: 1, name: 'rod'}, {id: 2, name: 'hey'}]))
{'1': 'rod', '2': 'hey'}

作为函数:

//    f :: Array { id :: String, name :: a } -> StrMap a
const f = R.pipe(R.indexBy(R.prop('id')), R.map(R.prop('name')));

f([{id: 1, name: 'rod'}, {id: 2, name: 'hey'}]);
// => {'1': 'rod', '2': 'hey'}

即使使用 Reduce 也会产生相当简洁和可读的代码:

reduce((acc, curr) => 
   R.assoc(curr.id, curr.name, acc), {}, arr)

或者如果用作函数:

const f = R.reduce((acc, curr) => 
   R.assoc(curr.id, curr.name, acc), {})