使用扩展运算符设置键名(Set keyname with spread operator)

编程入门 行业动态 更新时间:2024-10-17 21:20:22
使用扩展运算符设置键名(Set keyname with spread operator)

是否可以动态设置关键名称来传播运算符?

例如,我有:

'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 })));

Is it possible to dynamically set key name to spread operator?

For example I have:

'first, second, third'.split(','); // Array(3) : [ 'first', 'second', 'third' ]

I want to have an object like this

{ 'first': 'first', 'second': 'second', 'third': 'third' }

By doing this right now I get:

{ ...'first, second, third'.split(',') }; // { 1: 'first', 2: 'second', 3: 'third' }

Can I dynamically set it or I have to iterate through and do it manually at this point?

I've ended up combine the two answers to use this:

const toObject = str => Object.assign(...str.split(/\s*,\s*/).map(key => ({ [key]: key })));

最满意答案

乔纳斯的解决方案很聪明。 我喜欢。 这是一个替代方案:

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')); 
  
 

Jonas' solution is clever. I like it. Here's an alternative:

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')); 
  
 

Note that I use split(/\s*,\s*/) instead of split(',') to eliminate whitespace between parts.

This can be reduced to the following one-liner, if you're into that sort of thing:

const toObject = str =>
  str.split(/\s*,\s*/).reduce((o, p) => (o[p] = p, o), {});

console.log(toObject('first, second, third')); 
  
 

更多推荐

本文发布于:2023-07-25 05:44:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1256813.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:运算符   键名   Set   operator   spread

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!