how to spread an object to a function as arguments?

Although the other answers are correct, they change the function signature to accept an object instead of 2 separate arguments. Here is how to use an object's values as function arguments without altering the function's signature. This requires Object.values (ES 2017) and the spread operator to be available in your runtime.

const args = {
  a: 1,
  b: 2
}

const fn = (a, b) => a + b

fn(...Object.values(args));

Keep in mind this will work only in your specific case, since Object.values returns the values of all object keys and doesn't guarantee alphabetical sort order. If you want to take only the values of properties which are named a and b, you can map over Object.keys(args) and filter only those values.


The other answers are certainly applicable in particular situations, still have some limitations as well. Therefore I'd like to propose a different approach. The idea is to add to the object a method that returns an array of desired parameters in the appropriate order. That method is executed when passed to target function as argument and result destructured with spread operator.

const args = {
    a: 1,
    b: 2,
    argumentify: function () { 
        return [this.a, this.b]; 
    }
};

const fn = (a, b) => a + b;

console.log(fn(...args.argumentify()));

Benefits of this approach:

1) Does not require changes of the target function's signature, so can be used to ANY function.

2) Guarantees correct order of parameters (which is (as I understand) not guaranteed when spreading object).

3) Can itself be parametrized if needed.


You can use ES6 object destructuring on passed parameter and then just pass your object.

const args = {a: 1, b: 2}

const fn = ({a, b}) => a + b
console.log(fn(args))

You can also set default values for those properties.

const args = {b: 2}

const fn = ({a = 0, b = 0}) => a + b
console.log(fn(args))

Tags:

Javascript