最好的转换方式是什么:
['a','b','c']
to:
{
0: 'a',
1: 'b',
2: 'c'
}
最好的转换方式是什么:
['a','b','c']
to:
{
0: 'a',
1: 'b',
2: 'c'
}
当前回答
一个简单和厚脸皮的方法,快速转换数组的项目到一个对象
function arrayToObject( srcArray ){
return JSON.parse( JSON.stringify( srcArray ) );
}
然后像这样使用它…
var p = [0,2,3,'pork','pie',6];
obj = new arrayToObject( p );
console.log( obj[3], obj[4] )
// expecting `pork pie`
输出:
pork pie
检查类型:
typeof obj
"object"
如果没有原型方法,事情就不完整
Array.prototype.toObject =function(){
return JSON.parse( JSON.stringify( this ) );
}
使用:
var q = [0,2,3,'cheese','whizz',6];
obj = q.toObject();
console.log( obj[3], obj[4] )
// expecting `cheese whizz`
输出:
cheese whizz
*注意,没有命名例程,所以如果你想要特定的名称,那么你将需要继续使用下面现有的方法。
老的方法
这允许您从一个数组生成一个对象,其中的键是按照您想要的顺序定义的。
Array.prototype.toObject = function(keys){
var obj = {};
var tmp = this; // we want the original array intact.
if(keys.length == this.length){
var c = this.length-1;
while( c>=0 ){
obj[ keys[ c ] ] = tmp[c];
c--;
}
}
return obj;
};
result = ["cheese","paint",14,8].toObject([0,"onion",4,99]);
Console.log (">>>:" + result.onion);将输出"paint",函数必须有相等长度的数组,否则将得到一个空对象。
这里是一个更新的方法
Array.prototype.toObject = function(keys){
var obj = {};
if( keys.length == this.length)
while( keys.length )
obj[ keys.pop() ] = this[ keys.length ];
return obj;
};
其他回答
.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]
令I = 0; let myArray = ["first", "second", "third", "fourth"]; const arrayToObject = (arr) => 对象。分配(arr{},……。Map (item => ({[i++]: item}))); console.log (arrayToObject (myArray));
或使用
myArray = ["first", "second", "third", "fourth"] console.log (myArray{…})
为什么没人尝试?在ES6
let arr = ['a','b','c']
let {...obj} = arr
console.log(obj) // {0: 'a', 1: 'b', 2: 'c'}
let {...obj2} = ['a','b','c']
console.log(obj2) // {0: 'a', 1: 'b', 2: 'c'}
很简单的方法吗?
如果你使用ES6,你可以使用Object。赋值运算符和展开运算符
{ ...['a', 'b', 'c'] }
如果你有嵌套数组
var arr=[[1,2,3,4]]
Object.assign(...arr.map(d => ({[d[0]]: d[1]})))
你可以使用这样的函数:
var toObject = function(array) {
var o = {};
for (var property in array) {
if (String(property >>> 0) == property && property >>> 0 != 0xffffffff) {
o[i] = array[i];
}
}
return o;
};
这个方法可以更有效地处理稀疏数组。