1

I have a function that looks somewhat similar to the following:

foobar: function(arg1, arg2, arg3, ... argN) {
   // execute function
   // return result
}

In reality, this function takes a lot of arguments. I am not allowed to change the content of this function or the way it's built.

I also have an object:

inputObj: {
   arg1: val1,
   arg2: val2,
   // ...
   argN: valN
}

where the fields of this object match the parameters of the function foobar exactly -- in other words, the fields are spelt the same, they're added to the object in the same order, etc.

Does Javascript have an built-in function to either pass inputObj into the function foobar? Alternatively, does Javascript have an elegant way for me to split up the inputObj object into its contents such that the values are passed into the function according to their keys?

One possible solution, for example, could be:

const arg1 = inputObj['arg1'];
const arg2 = inputObj['arg2'];
// ...
const argN = inputObj['argN'];

foobar(arg1, arg2, ..., argN);

but I'm looking for a way to avoid writing out the whole code block as such to make it easier to read.

Thanks in advance!!

  • You can use `foobar(...Object.values(inputObj))`. But this depends on the properties being in the same order as the function parameters, which is not easy to ensure. So I wouldn't depend on it. – Barmar Sep 13 '22 at 21:16
  • But I don't think there's any other shortcut. – Barmar Sep 13 '22 at 21:16
  • I'm getting the following two errors when I attempt it (I call the function on slightly different objects both times):TypeError: Found non-callable @@iterator – Nathan Feldman Sep 13 '22 at 21:24
  • About this: `they're added to the object in the same order` Objects in JS have unordered properties. They may appear in order of how they were added, or alphabetical, or any other order. See https://stackoverflow.com/a/1069705/1220550 – Peter B Sep 13 '22 at 21:27
  • @PeterB See the updates in https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order – Barmar Sep 13 '22 at 21:30
  • Sorry for my previous comment. I was calling it with the spread operator in the wrong spot. I'm getting it working in some spots!!! Thanks! – Nathan Feldman Sep 13 '22 at 21:34
  • That said, there are some tests I'm running where I modify some fields which are not passing, I believe, because I'm modifying the order which Javascript iterates over the object – Nathan Feldman Sep 13 '22 at 21:37

1 Answers1

1

You can use destructuring.

const {arg1, arg2, ..., argN} = inputObj;
foobar(arg1, arg2, ..., argN);
Barmar
  • 741,623
  • 53
  • 500
  • 612