简体   繁体   中英

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

I need to turn this:

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

into:

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

That's what I tried:

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

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

mergeIdNames(o)

with the error:

mergeIdNames is not a function

You could use R.indexBy :

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

As a function:

//    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'}

Even using Reduce leads to a fairly terse and readable code:

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

Or if used as a function:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM