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

时间:2016-08-12 14:22:39

标签: javascript ramda.js

我需要转过身来:

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

2 个答案:

答案 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), {})