最好的转换方式是什么:
['a','b','c']
to:
{
0: 'a',
1: 'b',
2: 'c'
}
最好的转换方式是什么:
['a','b','c']
to:
{
0: 'a',
1: 'b',
2: 'c'
}
当前回答
打印稿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;
};
其他回答
最短的答案:(使用解构)
const obj = { ...input }
例子:
const inputArray = ["a", "b", "c"]
const outputObj = { ...inputArray }
令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{…})
如果有人在搜索Typescript方法,我这样写:
const arrayToObject = <T extends Record<K, any>, K extends keyof any>(
array: T[] = [],
getKey: (item: T) => K,
) =>
array.reduce((obj, cur) => {
const key = getKey(cur)
return ({...obj, [key]: cur})
}, {} as Record<K, T>)
它将:
强制第一个参数为对象数组 帮助选择键 强制该键为所有数组项的键
例子:
// from:
const array = [
{ sid: 123, name: 'aaa', extra: 1 },
{ sid: 456, name: 'bbb' },
{ sid: 789, name: 'ccc' }
];
// to:
{
'123': { sid: 123, name: 'aaa' },
'456': { sid: 456, name: 'bbb' },
'789': { sid: 789, name: 'ccc' }
}
用法:
const obj = arrayToObject(array, item => item.sid) // ok
const obj = arrayToObject(array, item => item.extra) // error
这是一个演示。
我们可以使用Object。赋值和数组。reduce函数将数组转换为对象。 Var arr = [{a:{b:1}},{c:{d:2}}] var newObj = arr。reduce((a, b) =>对象。赋值(a, b), {}) console.log (newObj)
var finalResult = ['a','b','c']。Map ((item, index) => ({[index]: item})); console.log (finalResult)