最好的转换方式是什么:
['a','b','c']
to:
{
0: 'a',
1: 'b',
2: 'c'
}
最好的转换方式是什么:
['a','b','c']
to:
{
0: 'a',
1: 'b',
2: 'c'
}
当前回答
如果可以使用Map或Object。分配,很简单。
创建一个数组:
const languages = ['css', 'javascript', 'php', 'html'];
下面的代码创建了一个以index为键的对象:
Object.assign({}, languages)
在地图上复制上面相同的操作
转换为基于索引的对象{0:'css'}等…
const indexMap = new Map(languages.map((name, i) => [i, name] ));
indexMap.get(1) // javascript
转换为一个基于值的对象{css: 'css是伟大的'}等…
const valueMap = new Map(languages.map(name => [name, `${name} is great!`] ));
valueMap.get('css') // css is great
其他回答
一个快速而肮脏的问题:
var obj = {},
arr = ['a','b','c'],
l = arr.length;
while( l && (obj[--l] = arr.pop() ) ){};
我会使用下划线,但如果没有的话我会使用reduce,初始值为空对象{}
>>> ['a', 'b', 'c'].reduce(function(p, c, i) {p[i] = c; return p}, {})
Object { 0="a", 1="b", 2="c"}
reduce应该在今天的大多数浏览器中广泛使用,参见MDN
使用javascript#forEach可以做到这一点
var result = {},
attributes = ['a', 'b','c'];
attributes.forEach(function(prop,index) {
result[index] = prop;
});
ECMA6:
attributes.forEach((prop,index)=>result[index] = prop);
FWIW,另一种最近的方法是使用Object. fromentries和Object。条目如下:
const arr = ['a','b','c'];
arr[-2] = 'd';
arr.hello = 'e';
arr.length = 17;
const obj = Object.fromEntries(Object.entries(arr));
...它允许避免将稀疏数组项存储为未定义或空,并保留非索引(例如,非正整数/非数字)键。
{0: "a", 1: "b", 2: "c", "-2": "d", hello: "e"}
(这里的结果与@Paul Draper的对象相同。分配的答案。)
你可能希望加上arr。长度,但不包括在内:
obj.length = arr.length;
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
}, {}),
};
};