简体   繁体   中英

Convert array of objects to plan 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 each is using a global variable result and i'm not sure how to avoid side effects here.

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM