我需要转过身来:
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
答案 0 :(得分:5)
您可以使用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'}
答案 1 :(得分:1)
即使使用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), {})