什么是将数组转换为对象的最佳方法,使得数组值成为新对象的键,空字符串成为新对象的值。
['a','b','c']
to:
{
a: '',
b: '',
c: ''
}
['a','b','c']
to:
{
a: '',
b: '',
c: ''
}
尝试使用Array.reduce():
const arr = ['a','b','c'];
const res = arr.reduce((acc,curr)=> (acc[curr]='',acc),{});
console.log(res)
acc[curr] = ''
。循环结束后,acc
会返回累加器。而 ,{}
表示累加器是一个对象。 - prasanthArray.prototype.reduce()
和 计算属性名
let arr = ['a','b','c'];
let obj = arr.reduce((ac,a) => ({...ac,[a]:''}),{});
console.log(obj);
const target = {}; ['a','b','c'].forEach(key => target[key] = "");
map
来迭代数组?你本可以选择 forEach
。 - Serge K.reduce
完美且方便的用法,所以我建议使用它。相较于 forEach
而言,reduce
更加简洁易懂,而且它也是为这种任务而设计的。因此,使用 reduce
并不会使代码变得“复杂”。 - user0103const array = Object.assign({},...["a","b","c"].map(key => ({[key]: ""})));
console.log(array);
curr
表示的键。
let k = ['a', 'b', 'c']
let obj = k.reduce(function(acc, curr) {
acc[curr] = '';
return acc;
}, {});
console.log(obj)
另一种选择是使用 for..of
循环
let k = ['a', 'b', 'c'];
const obj = {};
for (let keys of k) {
obj[keys] = '';
}
console.log(obj)
Object.fromEntries(['a', 'b', 'c'].map(k => [k, '']));
Object.fromEntries(['a', 'b', 'c'].map(k => [k, '']));
- luukvhoudt