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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)