【问题标题】:Set keyname with spread operator使用扩展运算符设置键名
【发布时间】: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


【解决方案1】:

您可以将键/值对列表传播到对象分配中:

  Object.assign(...'first, second, third'.split(',').map(key => ({[key]: key})))

【讨论】:

    【解决方案2】:

    乔纳斯的解决方案很聪明。我喜欢。这是另一种选择:

    function toObject(str) {
      const parts = str.split(/\s*,\s*/);
      return parts.reduce((obj, part) => {
        obj[part] = part;
        return obj;
      }, {});
    }
    
    console.log(toObject('first, second, third'));

    请注意,我使用split(/\s*,\s*/) 而不是split(',') 来消除部分之间的空白。

    如果你喜欢这样的事情,这可以简化为以下单行:

    const toObject = str =>
      str.split(/\s*,\s*/).reduce((o, p) => (o[p] = p, o), {});
    
    console.log(toObject('first, second, third'));

    【讨论】:

    • 还有str.split(",").map(x => x.trim()) - 它也消除了字符串前后的空格
    • 我接受这个答案是因为你有修剪空间的场景,当然还有单线:P
    猜你喜欢
    • 2018-05-17
    • 1970-01-01
    • 2011-09-09
    • 2018-12-09
    • 2018-12-16
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 2016-06-12
    相关资源
    最近更新 更多