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.
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 ).
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.
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.
compose FunctionPerforms right-to-left function composition. The rightmost function may have any arity; the remaining functions must be unary. See also pipe.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With