最好的转换方式是什么:
['a','b','c']
to:
{
0: 'a',
1: 'b',
2: 'c'
}
最好的转换方式是什么:
['a','b','c']
to:
{
0: 'a',
1: 'b',
2: 'c'
}
当前回答
使用javascript简化很简单:
["a", "b", "c", "d"].reduce(function(previousValue, currentValue, index) {
previousValue[index] = currentValue;
return previousValue;
},
{}
);
你可以看看Array.prototype.reduce(), https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
其他回答
这不是直接相关的,但我来这里寻找一个合并嵌套对象如一行
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}), {})
如果有人在搜索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
这是一个演示。
为了完整起见,这里有一个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
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
}, {}),
};
};
我会使用下划线,但如果没有的话我会使用reduce,初始值为空对象{}
>>> ['a', 'b', 'c'].reduce(function(p, c, i) {p[i] = c; return p}, {})
Object { 0="a", 1="b", 2="c"}
reduce应该在今天的大多数浏览器中广泛使用,参见MDN