5

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.

1
  • I think you want groupBy perhaps.
    – elclanrs
    Commented Dec 27, 2017 at 17:05

2 Answers 2

19

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:

-1

You can solve this with very basic reduce function.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.