Reputation: 8153
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?
Upvotes: 1
Views: 100
Reputation: 26181
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);
Upvotes: 0
Reputation: 386650
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);
Upvotes: 0
Reputation: 115232
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);
Upvotes: 1