最好的转换方式是什么:
['a','b','c']
to:
{
0: 'a',
1: 'b',
2: 'c'
}
最好的转换方式是什么:
['a','b','c']
to:
{
0: 'a',
1: 'b',
2: 'c'
}
当前回答
我会使用下划线,但如果没有的话我会使用reduce,初始值为空对象{}
>>> ['a', 'b', 'c'].reduce(function(p, c, i) {p[i] = c; return p}, {})
Object { 0="a", 1="b", 2="c"}
reduce应该在今天的大多数浏览器中广泛使用,参见MDN
其他回答
我可能会这样写(因为很少有我手边没有下划线库):
var _ = require('underscore');
var a = [ 'a', 'b', 'c' ];
var obj = _.extend({}, a);
console.log(obj);
// prints { '0': 'a', '1': 'b', '2': 'c' }
如果你喜欢联机程序,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});
}, {})
最简单的方法如下:
const arr = ['a','b','c'];
let obj = {}
function ConvertArr(arr) {
if (typeof(arr) === 'array') {
Object.assign(obj, arr);
}
这样它只在数组中运行,然而,你可以用let全局对象变量或不带,这取决于你,如果你不带let,只运行object。加勒比海盗,分配({})。
更面向对象的方法:
Array.prototype.toObject = function() {
var Obj={};
for(var i in this) {
if(typeof this[i] != "function") {
//Logic here
Obj[i]=this[i];
}
}
return Obj;
}
如果你想使用迭代对象的一个属性作为键,例如:
// from:
const arr = [
{
sid: 123,
name: 'aaa'
},
{
sid: 456,
name: 'bbb'
},
{
sid: 789,
name: 'ccc'
}
];
// to:
{
'123': { sid: 123, name: 'aaa' },
'456': { sid: 456, name: 'bbb' },
'789': { sid: 789, name: 'ccc' }
}
Use:
const result = arr.reduce((obj, cur) => ({...obj, [cur.sid]: cur}), {})