简体   繁体   中英

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.

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);

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

I don't know if this is more elegant but I think reduce make sence here.

 var items = [ { name: 'hello', value: ['one', 'two'] }, { name: 'hi', value: ['one', 'two', 'three'] } ]; const newObj = items.reduce((c, {value, name}) => { c[name] = value; return c; }, {}); console.log(newObj);

Simply by mapping each array elements:

use map() method:

const newObj = {};
items.map( ( { name, value } ) => {
    newObj[name] = value;
});

EDIT:

use forEach() method:

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

JavaScript: Difference between.forEach() and.map()

Use Object.values and Object.fromEntries to simplify into one line

Object.fromEntries(items.map(item => Object.values(item)))

 var items = [ { name: "hello", value: ["one", "two"] }, { name: "hi", value: ["one", "two", "three"] } ]; const res = Object.fromEntries(items.map(item => Object.values(item))); console.log(res);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM