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))
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.
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.
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.
The JavaScript spread operator ( ... ) allows us to quickly copy all or part of an existing array or object into another array or object.
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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With