Matthew Souther
Matthew Souther

Reputation: 1026

JavaScript functions: structured parameters as object?

I have a JavaScript function like this whose signature I don't want to change:

const myFunction(color, quantity) {
  ...
}

I want to use the function's structured parameters as if they're an object, like this:

const defaults = {color: 'blue', size: 'large'};
const myFunction(color, quantity) {
  // I know this won't work, because the JS arguments object is Array-like, 
  // and doesn't have named keys
  return { ...defaults, ...arguments };
}
console.log(myFunction(red, 22));
/* Should output:
  { color: 'red', size: 'large', quantity: 22 }
*/

Is there any way to access parameters like this?

Upvotes: 0

Views: 126

Answers (1)

Bergi
Bergi

Reputation: 664936

You have to explicitly spell out the parameter names to create an object from them - you can use the shorthand property syntax though:

{ color, size }

const defaults = {color: 'blue', size: 'large'};
function myFunction(color, quantity) {
  return { ...defaults, color, quantity };
}
console.log(myFunction('red', 22));

Upvotes: 1

Related Questions