13

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.

1
  • 1
    If I could give you 10 points for using RamdaJS I would... :+1: Commented Oct 17, 2019 at 18:06

3 Answers 3

24

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"}
Sign up to request clarification or add additional context in comments.

Comments

7

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.

Comments

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

1 Comment

reduce() is a very helpful suggestion, especially for more complicated cases.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.