Mansur
Mansur

Reputation: 412

Pass parameters as an object Javascript

In python there is a convenient way of passing a dict to a function instead of variables, like here

user = {
    'firstname':'John',
    'lastname': 'Wick'
}

def fullname(firstname, lastname):
    return firstname + ' ' + lastname

fullname(**user)
>>> 'John Wick'

instead of

fullname(user['firstname'], user['lastname'])
>>> 'John Wick'

Q: Is there a similar way of passing an object to a function instead of variables in javascript?

upd: function is unchangeable


I tried using the ... on the object, but it causes an error

user = {
    'firstname':'John',
    'lastname': 'Wick'
}

function fullname(firstname, lastname){
    return firstname + ' ' + lastname;
}

fullname(...user)
>>> Uncaught TypeError: Found non-callable @@iterator

Upvotes: 0

Views: 61

Answers (2)

Andy
Andy

Reputation: 63524

Pass in user, and then you can destructure the object parameter.

const user = {
  firstname: 'John',
  lastname: 'Wick'
};

function fullname({ firstname, lastname }){
  return `${firstname} ${lastname}`;
}

console.log(fullname(user));

Additional documentation

Upvotes: 0

moy2010
moy2010

Reputation: 902

I'm not at the pc, so this could be wrong by try this:

fullname(...Object.values(user))

Upvotes: 3

Related Questions