简体   繁体   English

将对象数组转换为键值对的 object

[英]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.这可能是 2 班轮,但由于某种原因,我碰壁了。

I'd like to convert an array of objects to an object of key-value pairs.我想将对象数组转换为键值对的 object。

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.我想最好使用 ES6 箭头函数。 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 :更简洁的方法是使用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() :我会用Array.prototype.reduce()来做到这一点,它比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.我不知道这是否更优雅,但我认为reduce在这里有意义。

 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:使用 map() 方法:

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

EDIT:编辑:

use forEach() method:使用 forEach() 方法:

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

JavaScript: Difference between.forEach() and.map() JavaScript:.forEach() 和.map() 之间的区别

Use Object.values and Object.fromEntries to simplify into one line使用Object.valuesObject.fromEntries简化为一行

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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