Monday, May 20, 2024
127
rated 0 times [  134] [ 7]  / answers: 1 / hits: 15570  / 8 Years ago, thu, may 5, 2016, 12:00:00

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.


More From » functional-programming

 Answers
31

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}

[#62302] Monday, May 2, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kennedysaraiw

Total Points: 552
Total Questions: 99
Total Answers: 109

Location: South Sudan
Member since Sun, Jul 11, 2021
3 Years ago
;