Javascript 将数组转换为对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4215737/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert Array to Object
提问by David Hellsing
What is the best way to convert:
什么是最好的转换方式:
['a','b','c']
to:
到:
{
0: 'a',
1: 'b',
2: 'c'
}
采纳答案by Oriol
ECMAScript 6 introduces the easily polyfillable Object.assign
:
ECMAScript 6 引入了易于填充的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()
方法用于将所有可枚举自身属性的值从一个或多个源对象复制到目标对象。它将返回目标对象。
Object.assign({}, ['a','b','c']); // {0:"a", 1:"b", 2:"c"}
The own length
property of the array is not copied because it isn't enumerable.
length
数组自己的属性不会被复制,因为它不可枚举。
Also, you can use ES6 spread syntaxto achieve the same result:
此外,您可以使用 ES6扩展语法来实现相同的结果:
{ ...['a', 'b', 'c'] }
回答by Pointy
With a function like this:
使用这样的功能:
function toObject(arr) {
var rv = {};
for (var i = 0; i < arr.length; ++i)
rv[i] = arr[i];
return rv;
}
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.
你的数组已经或多或少只是一个对象,但数组确实有一些关于整数命名属性的“有趣”和特殊行为。以上将为您提供一个简单的对象。
editoh also you might want to account for "holes" in the array:
编辑哦,您可能还想考虑数组中的“漏洞”:
function toObject(arr) {
var rv = {};
for (var i = 0; i < arr.length; ++i)
if (arr[i] !== undefined) rv[i] = arr[i];
return rv;
}
In modern JavaScript runtimes, you can use the .reduce()
method:
在现代 JavaScript 运行时中,您可以使用以下.reduce()
方法:
var obj = arr.reduce(function(acc, cur, i) {
acc[i] = cur;
return acc;
}, {});
That one also avoids "holes" in the array, because that's how .reduce()
works.
那个也避免了阵列中的“漏洞”,因为这就是.reduce()
工作原理。
回答by roland
You could use an accumulator aka reduce
.
您可以使用累加器 aka reduce
。
['a','b','c'].reduce(function(result, item, index, array) {
result[index] = item; //a, b, c
return result;
}, {}) //watch out the empty {}, which is passed as "result"
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"}
传递一个空对象{}
作为起点;然后逐步“增加”该对象。在迭代结束时,result
将{"0": "a", "1": "b", "2": "c"}
If your array is a set of key-value pair objects:
如果您的数组是一组键值对对象:
[{ a: 1},{ b: 2},{ c: 3}].reduce(function(result, item) {
var key = Object.keys(item)[0]; //first property: a, b, c
result[key] = item[key];
return result;
}, {});
will produce: {a: 1, b: 2, c: 3}
将产生: {a: 1, b: 2, c: 3}
For the sake of completeness, reduceRight
allows you to iterate over your array in reverse order:
为了完整起见,reduceRight
允许您以相反的顺序遍历数组:
[{ a: 1},{ b: 2},{ c: 3}].reduceRight(/* same implementation as above */)
will produce: {c:3, b:2, a:1}
将产生: {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 []
:
您的蓄能器可以是适合您特定目的的任何类型。例如,为了在数组中交换对象的键和值,请传递[]
:
[{ a: 1},{ b: 2},{ c: 3}].reduce(function(result, item, index) {
var key = Object.keys(item)[0]; //first property: a, b, c
var value = item[key];
var obj = {};
obj[value] = key;
result.push(obj);
return result;
}, []); //an empty array
will produce: [{1: "a"}, {2: "b"}, {3: "c"}]
将产生: [{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. Therefore reduce
allows you to achieve what filter
does, which makes reduce
very versatile:
与 不同map
,reduce
不能用作 1-1 映射。您可以完全控制要包含或排除的项目。因此reduce
可以让你实现什么filter
功能,这使得它reduce
非常通用:
[{ a: 1},{ b: 2},{ c: 3}].reduce(function(result, item, index) {
if(index !== 0) { //skip the first item
result.push(item);
}
return result;
}, []); //an empty array
will produce: [{2: "b"}, {3: "c"}]
将产生: [{2: "b"}, {3: "c"}]
Caution: reduce
and Object.key
are part of ECMA 5th edition
; you should provide a polyfill for browsers that don't support them (notably IE8).
注意:reduce
和Object.key
是ECMA 5th edition
; 您应该为不支持它们的浏览器(特别是 IE8)提供一个 polyfill。
See a default implementation by Mozilla.
查看Mozilla的默认实现。
回答by Max
If you're using jquery:
如果您使用的是 jquery:
$.extend({}, ['a', 'b', 'c']);
回答by mcmhav
For completeness, ECMAScript 2015(ES6) spreading. Will require either a transpiler(Babel) or an environment running at least ES6.
为了完整起见,ECMAScript 2015(ES6) 正在传播。将需要转译器(Babel)或至少运行 ES6 的环境。
console.log(
{ ...['a', 'b', 'c'] }
)
回答by Dave Dopson
I'd probably write it this way (since very rarely I'll not be having the underscorejs library at hand):
我可能会这样写(因为我很少会手头没有 underscorejs 库):
var _ = require('underscore');
var a = [ 'a', 'b', 'c' ];
var obj = _.extend({}, a);
console.log(obj);
// prints { '0': 'a', '1': 'b', '2': 'c' }
回答by Benjamin Gruenbaum
Here is an O(1) ES2015 method just for completeness.
这是一个 O(1) ES2015 方法,只是为了完整性。
var arr = [1, 2, 3, 4, 5]; // array, already an object
Object.setPrototypeOf(arr, Object.prototype); // now no longer an array, still an object
回答by Wylliam Judd
Surprised not to see -
没想到——
Object.assign({}, your_array)
回答by KARTHIKEYAN.A
we can use Object.assign
and array.reduce
function to convert an Array to Object.
我们可以使用Object.assign
和array.reduce
函数将数组转换为对象。
var arr = [{a:{b:1}},{c:{d:2}}]
var newObj = arr.reduce((a, b) => Object.assign(a, b), {})
console.log(newObj)