11

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.

customcommander
  • 11,496
  • 3
  • 35
  • 53
matiasfha
  • 1,220
  • 4
  • 23
  • 42

3 Answers3

20

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"}
Scott Sauyet
  • 37,179
  • 4
  • 36
  • 82
5

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.

jJ'
  • 2,890
  • 29
  • 25
3

Use reduce instead:

const arrayOfObject = [
     {KEY_A: 'asfas'}
    ,{KEY_B: 'asas' }
];
const each = R.reduce((acc,value) => { 
   const key = R.keys(value)[0];
   acc[key] = value[key];

   return acc;
},{},arrayOfObject);

Since your array is an array of objects, you could also just call merge inside a reduce:

const each2 = R.reduce((acc,value) => R.merge(value,acc),{},arrayOfObject);

Here is a jsbin with both examples: http://jsbin.com/mifohakeru/edit?js,console,output

iofjuupasli
  • 3,509
  • 1
  • 14
  • 17
Bless Yahu
  • 1,301
  • 1
  • 11
  • 25