Search code examples
javascriptecmascript-next

Set keyname with spread operator


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

Solution

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