如何将数组转换为对象?
: 的最佳方式是什么?
['a','b','c']
将: 转换为
{
0: 'a',
1: 'b',
2: 'c'
}
What is the best way to convert:
['a','b','c']
to:
{
0: 'a',
1: 'b',
2: 'c'
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(30)
ECMAScript 6 引入了易于填充的
对象。分配
:不会复制数组自身的
length
属性,因为它不可枚举。此外,您还可以使用 ES8 扩展语法对象来实现相同的结果:
对于自定义键,您可以使用
ECMAScript 6 introduces the easily polyfillable
Object.assign
:The own
length
property of the array is not copied because it isn't enumerable.Also, you can use ES8 spread syntax on objects to achieve the same result:
For custom keys you can use reduce:
使用这样的函数:
您的数组或多或少已经是一个对象,但数组确实有一些关于整数命名属性的“有趣”和特殊行为。上面会给你一个普通的对象。
编辑哦,您可能还想考虑数组中的“漏洞”:
在现代 JavaScript 运行时中,您可以使用
.reduce()
方法:该方法还可以避免“数组中的“洞”,因为这就是
.reduce()
的工作原理。With a function like this:
Your array already is more-or-less just an object, but arrays do have some "interesting" and special behavior with respect to integer-named properties. The above will give you a plain object.
edit oh also you might want to account for "holes" in the array:
In modern JavaScript runtimes, you can use the
.reduce()
method:That one also avoids "holes" in the array, because that's how
.reduce()
works.您可以使用累加器,又名
reduce< /代码>
。
传递一个空对象
{}
作为起点;然后逐步“增强”该对象。迭代结束时,
结果
将为{"0": "a", "1": "b", "2": "c"}
如果你的数组是一组键值对对象:
将产生:
{a: 1, b: 2, c: 3}
为了完整起见,
reduceRight
允许您以相反的顺序迭代数组:将产生:
{c:3, b:2, a:1}
您的累加器可以是适合您特定目的的任何类型。例如,为了交换数组中对象的键和值,请传递
[]
:将生成:
[{1: "a"}, {2: "b"} , {3: "c"}]
与
map
不同,reduce
不能用作 1-1 映射。您可以完全控制要包含或排除的项目。因此,reduce
允许您实现filter
的功能,这使得reduce
非常通用:将生成:
[{2: "b" }, {3: "c"}]
注意:
reduce
和Object.key
是ECMA 5th 的一部分版本
;你应该为不支持它们的浏览器(特别是 IE8)提供一个polyfill。请参阅 Mozilla 的默认实现。
You could use an accumulator aka
reduce
.Pass an empty object
{}
as a starting point; then "augment" that object incrementally.At the end of the iterations,
result
will be{"0": "a", "1": "b", "2": "c"}
If your array is a set of key-value pair objects:
will produce:
{a: 1, b: 2, c: 3}
For the sake of completeness,
reduceRight
allows you to iterate over your array in reverse order:will produce:
{c:3, b:2, a:1}
Your accumulator can be of any type for you specific purpose. For example in order to swap the key and value of your object in an array, pass
[]
:will produce:
[{1: "a"}, {2: "b"}, {3: "c"}]
Unlike
map
,reduce
may not be used as a 1-1 mapping. You have full control over the items you want to include or exclude. Thereforereduce
allows you to achieve whatfilter
does, which makesreduce
very versatile:will produce:
[{2: "b"}, {3: "c"}]
Caution:
reduce
andObject.key
are part ofECMA 5th edition
; you should provide a polyfill for browsers that don't support them (notably IE8).See a default implementation by Mozilla.
如果您使用 jquery:
If you're using jquery:
为了完整起见,ECMAScript 2015(ES6) 传播。需要一个转译器(Babel)或至少运行 ES6 的环境。
For completeness, ECMAScript 2015(ES6) spreading. Will require either a transpiler(Babel) or an environment running at least ES6.
这里没有多少人评论
Object.fromEntries
,我真的很喜欢它,因为它更干净并且可以轻松地与 TypeScript 一起使用,而无需过多担心泛型类型和内容。它还允许使用 map 自定义键,如果需要的话。缺点:如果您想要自定义密钥,则需要额外的地图
。例如:Not many people here commented of
Object.fromEntries
, I really enjoy it, since it's cleaner and works easily with TypeScript, without bothering too much about generic types and stuff. It also allows custom keys with map, if needed. Cons: you'll need an additionalmap
, if you want a custom key. E.g.:如果您想使用迭代对象的属性之一作为键,例如:
使用:
In case you want to use one of the properties of the iterated objects as key, for example:
Use:
我可能会这样写(因为我很少手头没有 underscorejs 库):
I'd probably write it this way (since very rarely I'll not be having the underscorejs library at hand):
我们可以使用
Object.assign
和array.reduce
函数将数组转换为对象。we can use
Object.assign
andarray.reduce
function to convert an Array to Object.这是一个 O(1) ES2015 方法,只是为了完整性。
Here is an O(1) ES2015 method just for completeness.
FWIW,最近的另一种方法是使用新的
Object.fromEntries
和Object.entries
,如下所示:...这允许避免将稀疏数组项存储为
undefined
或null
并保留非索引(例如,非正整数/非数字)键。(这里的结果与 @Paul Draper 的
Object.assign< /code> 答案。)
但是,人们可能希望添加
arr.length
,因为它不包括在内:FWIW, one another recent approach is to use the new
Object.fromEntries
along withObject.entries
as follows:...which allows for avoiding storing sparse array items as
undefined
ornull
and preserves non-index (e.g., non-positive-integer/non-numeric) keys.(Same result here as with @Paul Draper's
Object.assign
answer.)One may wish to add
arr.length
, however, as that is not included:如果您的数组包含双元素数组,其中第一个元素是键,第二个元素是值,您可以使用
reduce
轻松转换为对象。结果:
If your array contains 2-element arrays where first element is the key and second element is the value you can easily convert to object using
reduce
.Result:
使用
javascript#forEach
使用 ECMA6 可以做到这一点:
Using
javascript#forEach
one can do thisWith ECMA6:
如果您使用 ES6,则可以使用 Object.assign 和展开运算符
如果您有嵌套数组,例如
If you're using ES6, you can use Object.assign and the spread operator
If you have nested array like
最短的答案:(使用解构)
示例:
The shortest answer: (using destructuring)
Example:
一个快速而肮脏的:
A quick and dirty one:
支持更多浏览器和更灵活的方式是使用正常的循环,例如:
但现代的方式也可以使用< strong>扩展运算符,例如:
或对象分配:
两者都会返回:
More browser supported and more flexible way of doing that is using a normal loop, something like:
But also the modern way could be using the spread operator, like:
Or Object assign:
Both will return:
又快又脏#2:
Quick and dirty #2:
为什么没有人尝试这个?在 ES6 中
是非常简单的方法吗?
Why No One try this? in ES6
is Very simple way?
一种简单而厚颜无耻的方法,可以快速将项目数组转换为对象
然后像这样使用它...
输出:
检查类型:
如果没有原型方法,事情就不会完整
使用类似:
输出:
*注意,没有命名例程,因此如果您想要特定名称,则需要继续使用下面的现有方法。
较旧的方法
这允许您从数组生成一个对象,其中的键按照您想要的顺序定义。
console.log(">>> :" + result.onion);
将输出“paint”,该函数必须具有相等长度的数组,否则您将得到一个空对象。这是一个更新的方法
A simple and cheeky method of quickly converting an Array of items in to an Object
Then using it like so...
Output:
Checking the type:
AND things wouldn't be complete if there wasn't a prototype method
Using like:
Output:
*NOTE that there is no naming routine, so if you want to have specific names, then you will need to continue using the existing methods below.
Older method
This allows you to generate from an array an object with keys you define in the order you want them.
console.log(">>> :" + result.onion);
will output "paint", the function has to have arrays of equal length or you get an empty object.Here is an updated method
这是我刚刚写的一个递归函数。它很简单并且效果很好。
这是一个示例(jsFiddle):
结果:
Here's a recursive function I just wrote. It's simple and works well.
Here's an example (jsFiddle):
Results:
[文档]
或更详细
或更短
的普通 JS
一些更复杂的示例
甚至更短(通过使用
function(e) {console.log(e); return e;}
===(e)=>(console.log(e),e)
)[/docs]
[docs]
or more verbose
or
shortest one with vanilla JS
some more complex example
even shorter (by using
function(e) {console.log(e); return e;}
===(e)=>(console.log(e),e)
)[/docs]
从 Lodash 3.0.0 开始,您可以使用 _.toPlainObject
As of Lodash 3.0.0 you can use _.toPlainObject
如果您可以使用
Map
或Object.assign
,那就非常简单了。创建一个数组:
下面创建一个以索引为键的对象:
使用 Maps 复制与上面相同的内容
转换为基于索引的对象
{0 : 'css'}
等...转换为基于值对象
{css : 'css 很棒'}
等等...If you can use
Map
orObject.assign
, it's very easy.Create an array:
The below creates an object with index as keys:
Replicate the same as above with Maps
Converts to an index based object
{0 : 'css'}
etc...Convert to an value based object
{css : 'css is great'}
etc...我会简单地使用 Array.of() 来完成此操作。 Array of 能够将其上下文用作构造函数。
因此我们可以将 Array.of() 绑定到一个函数并生成一个类似数组的对象。
通过利用 Array.of() 人们甚至可以进行数组子类化。
I would do this simply with
Array.of()
. Array of has the ability to use it's context as a constructor.So we may bind
Array.of()
to a function and generate an array like object.By utilizing
Array.of()
one can even do array sub-classing.或者使用
Or use
ES5 - 解决方案:
使用Array原型函数'push'和'apply'你可以用以下内容填充对象数组元素。
ES5 - Solution:
Using Array prototype function 'push' and 'apply' you can populate the object with the array elements.
尝试使用 Reflect 从数组项复制到对象。
Try using reflect to copy from array item to object.
如果有人正在寻找 Typescript 方法,我会这样写:
它将:
示例:
用法:
这是一个演示。
If someone is searching for a Typescript method, i wrote this:
It will:
Example:
usage:
Here's a demo.
您可以使用这样的函数:
这个函数应该更有效地处理稀疏数组。
You could use a function like this:
This one should handle sparse arrays more efficiently.