最好的转换方式是什么:
['a','b','c']
to:
{
0: 'a',
1: 'b',
2: 'c'
}
最好的转换方式是什么:
['a','b','c']
to:
{
0: 'a',
1: 'b',
2: 'c'
}
当前回答
如果数组包含2元素数组,其中第一个元素是键,第二个元素是值,您可以使用reduce轻松地将其转换为对象。
[
["key1","value1"],
["key2", "value2"],
["key3", "value3"]
]
.reduce((acc, [key, value])=>({...acc, [key]: value}), {});
结果:
{
key1: 'value1',
key2: 'value2',
key3: 'value3'
}
其他回答
如果你使用ES6,你可以使用Object。赋值运算符和展开运算符
{ ...['a', 'b', 'c'] }
如果你有嵌套数组
var arr=[[1,2,3,4]]
Object.assign(...arr.map(d => ({[d[0]]: d[1]})))
最简单的方法如下:
const arr = ['a','b','c'];
let obj = {}
function ConvertArr(arr) {
if (typeof(arr) === 'array') {
Object.assign(obj, arr);
}
这样它只在数组中运行,然而,你可以用let全局对象变量或不带,这取决于你,如果你不带let,只运行object。加勒比海盗,分配({})。
import books from "./books.json";
export const getAllBooks = () => {
return {
data: books,
// a=accoumulator, b=book (data itelf), i=index
bookMap: books.reduce((a, book, i) => {
// since we passed {} as initial data, initially a={}
// {bookID1:book1, bookID2:i}
a[book.id] = book;
// you can add new property index
a[book.id].index=i
return a;
// we are passing initial data structure
}, {}),
};
};
如果有人在搜索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
这是一个演示。
使用javascript#forEach可以做到这一点
var result = {},
attributes = ['a', 'b','c'];
attributes.forEach(function(prop,index) {
result[index] = prop;
});
ECMA6:
attributes.forEach((prop,index)=>result[index] = prop);