1

Is there a good way to spread an object into parameters?

Say I have an object

const obj = {
  name: 'puppy',
  breed: 'poodle',
  weight: '7'
}

And a method such as this

const method = (name, breed, weight, height) => {
  // do something
}

I'd like to do something like this

method(...obj)

However, this obviously won't work because I can't spread an object like that. What can I do instead?

Andrew Zaw
  • 754
  • 1
  • 9
  • 16

3 Answers3

0

You can use destructuring to accomplish that, for example passing an object as parameter:

const obj = {
  name: 'puppy',
  breed: 'poodle',
  weight: '7'
}

const method = ({ name, breed, weight, height }) => {
  // do something
}

method(obj)
marcos
  • 4,473
  • 1
  • 10
  • 24
-1

It's pretty easy, all you have to do is deconstruct one parameter as an object in the function:

const obj = {
  name: 'puppy',
  breed: 'poodle',
  weight: '7'
}

const method = ({ name, breed, weight, height }) => {
  // do something
}

method(obj)
Isaac Corbrey
  • 553
  • 3
  • 20
-1

Try this, instead of spreading you can do a Destructuring of the object.

const obj = {
  name: 'puppy',
  breed: 'poodle',
  weight: '7'
}
const method = ({name,breed, weight}) => {
  console.log(name, breed, weight)
}

method(obj)
Learner
  • 8,379
  • 7
  • 44
  • 82