Monday, May 20, 2024
170
rated 0 times [  174] [ 4]  / answers: 1 / hits: 18977  / 7 Years ago, thu, december 28, 2017, 12:00:00

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))

More From » spread-syntax

 Answers
23

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))




[#55586] Thursday, December 21, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
myrap

Total Points: 407
Total Questions: 105
Total Answers: 109

Location: Cambodia
Member since Thu, Oct 7, 2021
3 Years ago
myrap questions
Tue, Feb 8, 22, 00:00, 2 Years ago
Wed, Jan 15, 20, 00:00, 4 Years ago
Thu, Oct 24, 19, 00:00, 5 Years ago
Thu, Oct 3, 19, 00:00, 5 Years ago
Mon, Aug 12, 19, 00:00, 5 Years ago
;