1

I have the following:

const a = (...args) =>{ return {...args}}
const abc = a('lol', 'rofl', 'lmao');
console.log('abc', abc);

However, this prints out

Object {0: "lol", 1: "rofl", 2: "lmao"}

But I expected

Object {lol: "lol", rofl: "rofl", lmao: "lmao"}

since

{lol, rofl, lmao}

produces the line above.

Is there a way to spread the arguments so that I can get this result?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
TheRealFakeNews
  • 7,512
  • 16
  • 73
  • 114
  • 1
    FWIW this is not Ecmascript-6. – lonesomeday Mar 16 '17 at 15:04
  • @lonesomeday What? – mhodges Mar 16 '17 at 15:43
  • 1
    I think the OP is trying to dynamically generate objects using the short-hand syntax provided in ES6, which i'm not sure if it is possible or not. – mhodges Mar 16 '17 at 15:45
  • So, using the spread/rest operator within object destructuring is experimental and is not part of the official ES2015 spec. This may be a feature that makes the spec down the road, but as of right now, it is not possible. Kyle Simpson talks about this in his "ES6: The Right Parts" workshop – mhodges Mar 16 '17 at 16:07
  • 3
    [`...` is not an operator](https://stackoverflow.com/questions/37151966/what-is-spreadelement-in-ecmascript-documentation-is-it-the-same-as-spread-oper/37152508#37152508)! And `{...args}` is not the same as `{lol, rofl, lmao}`. Object spread is equivalent to using `Object.assign`: `Object.assign({}, args)`. `args` is an array (of strings), that's why you are getting this result. – Felix Kling Mar 16 '17 at 16:24

3 Answers3

1

I don't think that there is any build in method to do that, the spread syntax will not work as you expected. Anyway, you can use Array#reduce method.

const a = (...args) => args.reduce((obj, v) => (obj[v] = v, obj), {})
const abc = a('lol', 'rofl', 'lmao');
console.log('abc', abc);
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
0

You could use Object.assign and computed properties.

const a = (...args) => args.reduce((obj, v) => Object.assign(obj, { [v]: v }), {});
const abc = a('lol', 'rofl', 'lmao');

console.log('abc', abc);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You may do as follows;

function F(...args){
  args.forEach(a => this[a] = a, this);
}
var abc = new F('lol', 'rofl', 'lmao');
console.log('abc', abc);
Redu
  • 25,060
  • 6
  • 56
  • 76
  • Why introduce `new`? – Bergi Mar 16 '17 at 20:55
  • @Bergi Because `F` is not a factory and i am not returning anything from the constructor. But i am pretty sure you have something hidden in your pocket. Ok let's see it. :) – Redu Mar 16 '17 at 20:59
  • I mean, why use a constructor at all? It *should* be a factory function. – Bergi Mar 16 '17 at 21:03
  • @Bergi, Hmm may be yes may be no. One reason might be a need to populate the `F.prototype` later. – Redu Mar 16 '17 at 21:16
  • OP wanted a plan `Object`, not something that inherits from a custom prototype – Bergi Mar 16 '17 at 21:42