4

I have many functions defined elsewhere that look like this

export function foo(bar1, bar2, bar3, ...) {
  // does stuff
}

In the module I am working on I am passed both the function above and an object containing the parameters like this:

// params = {
//   bar1: bar1Value,
//   bar2: bar2Value,
//   bar3: bar3Value,
//   ...
// }
function myFunc(foo, params) {

}

I need to call func with the params in the correct order. It is an object not an array so I can't rely on the property order, I need to match up the params to the signature of the function. Is this possible?

Edit to add: There are hundreds of functions that can be passed in, I am trying to avoid refactoring them all, but it seems that it is impossible to look up the parameter names directly. However I've found this which shows it can be done by breaking down the function as a string.

Cœur
  • 37,241
  • 25
  • 195
  • 267
SystemicPlural
  • 5,629
  • 9
  • 49
  • 74
  • 1
    actually it is not possible, because the parameter names are not readable. – Nina Scholz Aug 10 '18 at 11:01
  • 1
    are the properties of params called bar1, bar2 etc (or do you know their names)? If so, its possible – Ahorn Aug 10 '18 at 11:02
  • As @NinaScholz said, you can’t do this dynamically. You may want to use an object as an argument though: `function foo({ bar1, bar2, bar3 }) { ... }` – Iso Aug 10 '18 at 11:06

1 Answers1

0

You can access the properties of an object (like "params") either like params.bar1 or like params["bar1"] and you can get the names of the properties by using Object.keys(params), if thats what your asking for.

See also https://www.w3schools.com/js/js_object_properties.asp and https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Ahorn
  • 649
  • 4
  • 19