1

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 })));
Felix Kling
  • 756,363
  • 169
  • 1,062
  • 1,111
Ali
  • 9,177
  • 18
  • 69
  • 102
  • 1
    You cannot spread an array into object keys. – Bergi Feb 21 '18 at 21:10
  • 1
    [`...` is not an operator!](https://stackoverflow.com/questions/37151966/what-is-spreadelement-in-ecmascript-documentation-is-it-the-same-as-spread-oper/37152508#37152508) – Felix Kling Feb 24 '18 at 05:46

2 Answers2

4

You could spread a list of key/value pairs into object assign:

  Object.assign(...'first, second, third'.split(',').map(key => ({[key]: key})))
Jonas Wilms
  • 120,546
  • 16
  • 121
  • 140
2

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'));
Jordan Running
  • 97,653
  • 15
  • 175
  • 173
  • 1
    Also `str.split(",").map(x => x.trim())` - which eliminates whitespace in front and end of the string as well – Bergi Feb 21 '18 at 21:11
  • I'm accepting this answer because you have the scenario for trimming space and of course one-liner :P – Ali Feb 21 '18 at 22:54