【发布时间】:2018-08-01 14:08:39
【问题描述】:
是否可以动态设置键名到展开操作符?
例如我有:
'first, second, third'.split(',');
// Array(3) : [ 'first', 'second', 'third' ]
我想要一个这样的对象
{ 'first': 'first', 'second': 'second', 'third': 'third' }
现在通过这样做,我得到:
{ ...'first, second, third'.split(',') };
// { 1: 'first', 2: 'second', 3: 'third' }
我可以动态设置它还是我必须迭代并在此时手动执行?
我最终将这两个答案结合起来使用:
const toObject = str => Object.assign(...str.split(/\s*,\s*/).map(key => ({ [key]: key })));
【问题讨论】:
-
您不能将数组传播到对象键中。
标签: javascript ecmascript-next