什么是最好的方法来转换一个数组,以这些数组值作为键的对象,空字符串作为新对象的值。
['a','b','c']
致:
{ a: '', b: '', c: '' }
You can use array reduce function & pass an empty object in the accumulator. In this accumulator add key which is denoted by curr
curr
let k = ['a', 'b', 'c'] let obj = k.reduce(function(acc, curr) { acc[curr] = ''; return acc; }, {}); console.log(obj)
You can use Array.prototype.reduce()and Computed property names
Array.prototype.reduce()
let arr = ['a','b','c']; let obj = arr.reduce((ac,a) => ({...ac,[a]:''}),{}); console.log(obj);
try with Array#Reduce
Array#Reduce
const arr = ['a','b','c']; const res = arr.reduce((acc,curr)=> (acc[curr]='',acc),{}); console.log(res)
You can use Object.assign property to combine objects created with a map function, please take into account that if values of array elements are not unique the latter ones will overwrite previous ones
const array = Object.assign({},...["a","b","c"].map(key => ({[key]: ""}))); console.log(array);
var target = {}; ['a','b','c'].forEach(key => target[key] = "");