Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert array of objects to one Object using ramda.js

I have an array:

var a = [
    {id: 1, val: 'a'},
    {id: 2, val: 'b'},
    {id: 3, val: 'c'},
    {id: 4, val: 'd'},
]

And I want to get transform it to:

var b = {
    1: 'a',
    2: 'b',
    3: 'c',
    4: 'd',
}

Actually I'm using pure js:

var b = a.reduce(
    (ac, pr) => ({
      ...ac,
      [pr.id]: pr.val,
    }),
    {}
  );

But maybe Ramda.js have something special for that purpose?

like image 669
n06rin Avatar asked Nov 27 '17 08:11

n06rin


2 Answers

You are looking for Ramda's .mergeAll() method:

var b = R.mergeAll(a.map(function(o) {
  return {
    [o.id]: o.val
  }
}));

The .map()call will return the custom object from each item, taking only the values, then .mergeAll() will merge the array into one object.

mergeAll Documentation:

Merges a list of objects together into one object.

Demo:

var a = [{
    id: 1,
    val: 'a'
  },
  {
    id: 2,
    val: 'b'
  },
  {
    id: 3,
    val: 'c'
  },
  {
    id: 4,
    val: 'd'
  },
];


var b = R.mergeAll(a.map(function(o) {
  return {
    [o.id]: o.val
  }
}));
console.log(b);
<script src="https://cdn.jsdelivr.net/ramda/0.18.0/ramda.min.js"></script>
like image 176
cнŝdk Avatar answered Nov 14 '22 22:11

cнŝdk


If anyone still passes by here, it does indeed:

R.indexBy(R.prop('id'), someArray);

See indexBy in Ramda's documentation

EDIT: Bennet is correct. If we want val as the only value per key, we can "pluck" it out after:

const createValDict = R.pipe(
  R.indexBy(R.prop('id')),
  R.pluck('val')
)

const valDict = createValDict(myArr)

Pluck works on objects too

like image 22
Fredric Waadeland Avatar answered Nov 14 '22 22:11

Fredric Waadeland