Convert array of objects to plain object using Ramda

13,467

Solution 1

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"}

Solution 2

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.

Solution 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

Share:
13,467
matiasfha
Author by

matiasfha

I'm a software developer writing lines of code from the south of the world. Based in Talca, Chile. Proud father and husband. Freelance Software Engineer Hire me at https://www.linkedin.com/in/mhernand/

Updated on June 14, 2022

Comments

  • matiasfha
    matiasfha almost 2 years

    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.

  • DaveGauer
    DaveGauer over 6 years
    reduce() is a very helpful suggestion, especially for more complicated cases.