Search code examples
javascriptarraysecmascript-6key-valuetopological-sort

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.


Solution

  • 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%;}