最好的转换方式是什么:
['a','b','c']
to:
{
0: 'a',
1: 'b',
2: 'c'
}
最好的转换方式是什么:
['a','b','c']
to:
{
0: 'a',
1: 'b',
2: 'c'
}
当前回答
我将使用Array.of()简单地做到这一点。Array of有能力使用它的context作为构造函数。
注2:of函数是一个有意通用的工厂方法;它 不要求它的this值是数组构造函数。 因此,它可以传递给其他构造函数或由其他构造函数继承 可以使用单个数值参数调用。
因此,我们可以将array .of()绑定到一个函数,并生成类似object的数组。
虚函数(){}; var thingy = Array.of.apply(dummy,[1,2,3,4]); console.log(页面);
通过使用array .of(),甚至可以进行数组子类化。
其他回答
快速和肮脏的#2:
var i = 0
, s = {}
, a = ['A', 'B', 'C'];
while( i < a.length ) { s[i] = a[i++] };
更面向对象的方法:
Array.prototype.toObject = function() {
var Obj={};
for(var i in this) {
if(typeof this[i] != "function") {
//Logic here
Obj[i]=this[i];
}
}
return Obj;
}
如果你喜欢联机程序,IE8不再是一个问题(因为它应该是)
['a','b','c'].reduce((m,e,i) => Object.assign(m, {[i]: e}), {});
继续在浏览器控制台上尝试它
它可以像这样更啰嗦:
['a','b','c'].reduce(function(memo,elm,idx) {
return Object.assign(memo, {[idx]: elm});
}, {});
但还是排除了IE8的可能性。如果必须使用IE8,那么你可以像这样使用lodash/下划线:
_.reduce(['a','b','c'], function(memo,elm,idx) {
return Object.assign(memo, {[idx]: elm});
}, {})
我的版本数组json在JS。只需要复制/粘贴并使用它。这是不是很棒?我喜欢我在StackOverflow上发现的这类函数。
function array2json(arr) {
var parts = [];
var is_list = (Object.prototype.toString.apply(arr) === '[object Array]');
for(var key in arr) {
var value = arr[key];
if(typeof value == "object") { //Custom handling for arrays
if(is_list) parts.push(array2json(value)); /* :RECURSION: */
else parts[key] = array2json(value); /* :RECURSION: */
} else {
var str = "";
if(!is_list) str = '"' + key + '":';
//Custom handling for multiple data types
if(typeof value == "number") str += value; //Numbers
else if(value === false) str += 'false'; //The booleans
else if(value === true) str += 'true';
else str += '"' + value + '"'; //All other things
// :TODO: Is there any more datatype we should be in the lookout for? (Functions?)
parts.push(str);
}
}
var json = parts.join(",");
if(is_list) return '[' + json + ']';//Return numerical JSON
return '{' + json + '}';//Return associative JSON
}
.reduce((o,v,i)=>(o[i]=v,o), {})
(文档)
或者更冗长
var trAr2Obj = function (arr) {return arr.reduce((o,v,i)=>(o[i]=v,o), {});}
or
var transposeAr2Obj = arr=>arr.reduce((o,v,i)=>(o[i]=v,o), {})
最短的一个香草JS
JSON.stringify([["a", "X"], ["b", "Y"]].reduce((o,v,i)=>{return o[i]=v,o}, {}))
=> "{"0":["a","X"],"1":["b","Y"]}"
更复杂的例子
[["a", "X"], ["b", "Y"]].reduce((o,v,i)=>{return o[v[0]]=v.slice(1)[0],o}, {})
=> Object {a: "X", b: "Y"}
甚至更短(通过使用函数(e) {console.log(e);} === (e)=>(console.log(e),e))
nodejs
> [[1, 2, 3], [3,4,5]].reduce((o,v,i)=>(o[v[0]]=v.slice(1),o), {})
{ '1': [ 2, 3 ], '3': [ 4, 5 ] }
[/ docs]