Golo Roden Golo Roden - 4 months ago 16
Javascript Question

Convert arguments to object?

I'm looking for a way to transform a list of function arguments to a single object, where each argument results in a property on the object with the appropriate name.

Basically, what I want to achieve is something such as:

const foo = function (a, b, c) {
const args = getObjectFromArguments(a, b, c);
// or: getObjectFromArguments(arguments);
// or: getObjectFromArguments();

console.log(args);
// { a: 2, b: 3, c: 4 }
};

foo(2, 3, 4);


How can I do this without the need to provide the arguments' names as reference and as a string, ideally even without using more complex constructs? The call to
getObjectFromArguments
should be as simple as possible.

Any ideas?

Answer

A function is superfluous for this. The functionality you are looking for is part of the ES6 syntax. You just need to write { a, b, c } instead of uselessFunction(a, b, c).

const foo = function (a, b, c) {
  const args = { a, b, c };
  console.log(args);
};

foo(2, 3, 4);

Comments