最好的转换方式是什么:
['a','b','c']
to:
{
0: 'a',
1: 'b',
2: 'c'
}
最好的转换方式是什么:
['a','b','c']
to:
{
0: 'a',
1: 'b',
2: 'c'
}
当前回答
更多的浏览器支持和更灵活的方法是使用一个正常的循环,比如:
const arr = ['a', 'b', 'c'],
obj = {};
for (let i=0; i<arr.length; i++) {
obj[i] = arr[i];
}
但现代的方法也可以使用展开运算符,比如:
{...arr}
或对象赋值:
Object.assign({}, ['a', 'b', 'c']);
两者都会返回:
{0: "a", 1: "b", 2: "c"}
其他回答
快速和肮脏的#2:
var i = 0
, s = {}
, a = ['A', 'B', 'C'];
while( i < a.length ) { s[i] = a[i++] };
这不是直接相关的,但我来这里寻找一个合并嵌套对象如一行
const nodes = {
node1: {
interfaces: {if1: {}, if2: {}}
},
node2: {
interfaces: {if3: {}, if4: {}}
},
node3: {
interfaces: {if5: {}, if6: {}}
},
}
解决方案是结合使用reduce和对象扩展:
const allInterfaces = nodes => Object.keys(nodes).reduce((res, key) => ({...res, ...nodes[key].interfaces}), {})
.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]
如果你正在使用jquery:
$.extend({}, ['a', 'b', 'c']);
这里没有多少人评论Object.fromEntries,我真的很喜欢它,因为它更干净,很容易与TypeScript一起工作,不需要太多泛型类型和东西。如果需要,它还允许使用map自定义键。缺点:如果你想要一个自定义键,你将需要一个额外的映射。例如:
const tags = [
{ name: 'AgeGroup', value: ageGroup },
{ name: 'ApparelTypes', value: apparelTypes },
{ name: 'Brand', value: brand },
// ...
]
const objectTags = Object.fromEntries(tags.map((t) => [t.name, t.value]))
/*
{
AgeGroup: 'Adult',
Apparel: 'Creeper, Jacket'
Brand: '',
// ...
}
*/