JavaScript Ramdajs keyBy equivalent of lodash

I have an array that I want to transform into an object. For example:

const arr = [{id: 1, key: ''}, {id: 2, key: ''}];

I want the result to be:

const object = { 1: {id: 1, key: ''}, 2: { id: 2, key: ''}}

With lodash I can use the keyBy function, but I am working with ramda and did not find this functionality there.

Answer:1

You can solve this with very basic reduce function.

function keyBy(entities, id = "id") {
   entities.reduce((acc, entity) => {
      acc[entity[id]] = entity;
      return acc;
    }, {});
}
Answer:2

In case anyone still finds this via search, the correct answer is indexBy, added in mid-2016.

const list = [{id: 'xyz', title: 'A'}, {id: 'abc', title: 'B'}];
R.indexBy(R.prop('id'), list);
//=> {abc: {id: 'abc', title: 'B'}, xyz: {id: 'xyz', title: 'A'}}

See Also:

Answer:3

I tried creating mixing in a getter into a JS object via the spread operator syntax, however it always seems to return null. HTML: <body> <div id="wrapperA"></div> <div id="...

I tried creating mixing in a getter into a JS object via the spread operator syntax, however it always seems to return null. HTML: <body> <div id="wrapperA"></div> <div id="...

I have an two elements fruits and crates fruits is an array containing a list of different fruits like: ["apple","orange","mango","pear"] crates is an array of objects which contains fruits in it ...

I have an two elements fruits and crates fruits is an array containing a list of different fruits like: ["apple","orange","mango","pear"] crates is an array of objects which contains fruits in it ...

How can I translate this curl script to an AJAX request in JavaScript? curl -X POST -d "grant_type=password&username=admin&password=Demo1234" -u "<ClientID>:<ClientSecret&...

How can I translate this curl script to an AJAX request in JavaScript? curl -X POST -d "grant_type=password&username=admin&password=Demo1234" -u "<ClientID>:<ClientSecret&...

  1. translate curl to javascript

I'm a bit confused after reading about how to use bitmasks to store boolean values. I would like to have a set of boolean values and then generate a unique integer for each combination of the values. ...

I'm a bit confused after reading about how to use bitmasks to store boolean values. I would like to have a set of boolean values and then generate a unique integer for each combination of the values. ...