Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to spread an object to a function as arguments?

Tags:

I have an object an a function which accept arguments, I would like to spread the objects so each property is an argument in that function.

What am I doing wrong in my code?

const args = {
    a: 1
    b: 2
}

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

// i am trying with no success
console.log(fn(...args))
like image 881
Radex Avatar asked Dec 28 '17 13:12

Radex


People also ask

Can object be an argument?

You can pass an object as an argument in the usual way. We've already seen this in some of the turtle examples where we passed the turtle to some function like drawRectangle so that the function could control and use whatever turtle instance we passed to it.

Can you use spread operator on objects?

Spread syntax can be used when all elements from an object or array need to be included in a new array or object, or should be applied one-by-one in a function call's arguments list.

Can you spread an object JavaScript?

Use the object spread operator to clone an object or merge objects into one. Cloning is always shallow. When merging objects, the spread operator defines new properties while the Object.

What is spread function in JavaScript?

The JavaScript spread operator ( ... ) allows us to quickly copy all or part of an existing array or object into another array or object.


2 Answers

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.

like image 105
Tsvetan Ganev Avatar answered Sep 21 '22 15:09

Tsvetan Ganev


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))
like image 22
Nenad Vracar Avatar answered Sep 20 '22 15:09

Nenad Vracar