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
  • 795,719
  • 175
  • 1,089
  • 1,143
Ali
  • 9,997
  • 20
  • 70
  • 105
  • 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
  • 132,000
  • 20
  • 149
  • 151
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
  • 102,619
  • 17
  • 182
  • 182
  • 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