是否可以动态设置关键名称来传播运算符?
例如,我有:
'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'));
更多推荐
发布评论