最好的转换方式是什么:
['a','b','c']
to:
{
0: 'a',
1: 'b',
2: 'c'
}
最好的转换方式是什么:
['a','b','c']
to:
{
0: 'a',
1: 'b',
2: 'c'
}
当前回答
尝试使用反射从数组项复制到对象。
var arr =['aa:23','bb:44','cc:55']
var obj ={}
arr.forEach(e => {
var ee = e.split(':')
Reflect.set(obj,ee[0],ee[1])
});
console.log(obj) // { aa: '23', bb: '44', cc: '55' }
其他回答
.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]
更面向对象的方法:
Array.prototype.toObject = function() {
var Obj={};
for(var i in this) {
if(typeof this[i] != "function") {
//Logic here
Obj[i]=this[i];
}
}
return Obj;
}
为了完整起见,这里有一个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
使用javascript lodash库。有一个简单的方法 _。[iteratee = _.identity] mapKeys(对象) 可以进行转换。
打印稿solutioin:
export const toMap = (errors: ResponseError[]) => {
const errorMap: Record<string, string> = {};
errors.forEach(({ field, message }) => {
errorMap[field] = message;
});
return errorMap;
};
export type FieldError = {
field: string;
message: string;
};