Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert array of objects to object of key-value pairs

This is probably a 2 liner, but for some reason I have hit a wall.

I'd like to convert an array of objects to an object of key-value pairs.

So this:

var items = [
    {
      name: 'hello',
      value: ['one', 'two']
    },
    {
      name: 'hi',
      value: ['one', 'two', 'three']
    }
]

to this:

var items = {
    'hello': ['one', 'two'],
    'hi': ['one', 'two', 'three']
}

Is this really the most elegant way?

const newObj = {};
items.forEach((item) => {
  newObj[item.name] = item.value;
});

I'd like to use ES6 arrow functions preferably. Also, can someone tell me if you think it would be easier to manipulate this data in the first or second format? For context, I am trying to teach myself topological sorts.

like image 904
bspckl Avatar asked Apr 18 '20 22:04

bspckl


2 Answers

I would do that with Array.prototype.reduce(), it is even more concise and certainly faster than Object.fromEntries():

const items = [{name:'hello',value:['one','two']},{name:'hi',value:['one','two','three']}], 

result = items.reduce((r,{name,value}) => (r[name]=value,r), {})

console.log(result)
.as-console-wrapper{min-height:100%;}
like image 120
Yevgen Gorbunkov Avatar answered Sep 29 '22 23:09

Yevgen Gorbunkov


A more concise method would be to use Object.fromEntries:

var items = [
    {
      name: 'hello',
      value: ['one', 'two']
    },
    {
      name: 'hi',
      value: ['one', 'two', 'three']
    }
];
const newObj = Object.fromEntries(
  items.map(({ name, value }) => [name, value])
);
console.log(newObj);
like image 22
CertainPerformance Avatar answered Sep 29 '22 23:09

CertainPerformance