Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert array of objects to plain object using Ramda

How can I convert an array of objects to a plain object? Where each item of the array is an object with only one key:value pair and the key have an unknown name.

I have this

const arrayOfObject = [
    {KEY_A: 'asfas'},
    {KEY_B: 'asas' }
]
let result = {} 
const each = R.forEach((item) => {
   const key = R.keys(item)[0]
    result[key] = item[key]
})
return result

But I dislike that solution because the forEach is using a global variable result and I'm not sure how to avoid side effects here.

like image 811
matiasfha Avatar asked May 05 '16 00:05

matiasfha


People also ask

Is ramda better than Lodash?

Ramda is generally a better approach for functional programming as it was designed for this and has a community established in this sense. Lodash is generally better otherwise when needing specific functions (esp. debounce ).

What is Ramda in JavaScript?

Ramda is a JavaScript library that makes functional programming simple. While JavaScript libraries with functional capabilities have been around for a while, Ramda acts as a complete standard library specifically catered to the functional paradigm. Ramda is a JavaScript library that makes functional programming simple.

Should I use ramda?

Yep. Ramda is an excellent library for getting started on thinking functionally with JavaScript. Ramda provides a great toolbox with a lot of useful functionality and decent documentation. If you'd like to try the functionality as we go, check out Ramda's REPL.

What is compose in ramda?

compose FunctionPerforms right-to-left function composition. The rightmost function may have any arity; the remaining functions must be unary. See also pipe.


2 Answers

Ramda has a function built-in for this, mergeAll.

const arrayOfObject = [
     {KEY_A: 'asfas'}
    ,{KEY_B: 'asas' }
];

R.mergeAll(arrayOfObject); 
//=> {"KEY_A": "asfas", "KEY_B": "asas"}
like image 96
Scott Sauyet Avatar answered Sep 21 '22 08:09

Scott Sauyet


Since everybody is using ES6 already (const), there is a nice pure ES6 solution:

const arrayOfObject = [
  {KEY_A: 'asfas'},
  {KEY_B: 'asas'}
];

Object.assign({}, ...arrayOfObject);
//=> {KEY_A: "asfas", KEY_B: "asas"}

Object.assing merges provided objects to the first one, ... is used to expand an array to the list of parameters.

like image 28
jJ' Avatar answered Sep 19 '22 08:09

jJ'