将数组转换为对象 [英] Convert Array to Object
本文介绍了将数组转换为对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
最好的转换方式是:
['a','b','c']
到:
{
0: 'a',
1: 'b',
2: 'c'
}
推荐答案
ECMAScript 6 引入了易于填充的 Object.assign
:
ECMAScript 6 introduces the easily polyfillable Object.assign
:
Object.assign()
方法用于复制所有从一个或多个源对象到目标的可枚举自身属性目的.它将返回目标对象.
The
Object.assign()
method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.
Object.assign({}, ['a','b','c']); // {0:"a", 1:"b", 2:"c"}
数组自身的length
属性没有被复制,因为它不可枚举.
The own length
property of the array is not copied because it isn't enumerable.
此外,您可以使用 ES8 扩展语法 在对象上达到相同的结果:
Also, you can use ES8 spread syntax on objects to achieve the same result:
{ ...['a', 'b', 'c'] }
对于自定义键,您可以使用 reduce:
For custom keys you can use reduce:
['a', 'b', 'c'].reduce((a, v) => ({ ...a, [v]: v}), {})
// { a: "a", b: "b", c: "c" }
这篇关于将数组转换为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文