0

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
Mansur
  • 182
  • 2
  • 8
  • I don't think there is a complete equivalent, though, as in Python one can pass `user = { 'lastname': 'Wick', 'firstname':'John', }` and it would help you reorder things. – qrsngky Aug 12 '22 at 06:09

2 Answers2

3

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

fullname(...Object.values(user))
moy2010
  • 854
  • 12
  • 18
  • 2
    For this you possibly want to check that object property order is guaranteed for your environment. https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order – Ben Stephens Aug 12 '22 at 06:11
  • Try passing `user = { 'lastname': 'Wick', 'firstname':'John', }` and see the results. – qrsngky Aug 12 '22 at 06:12
0

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

Andy
  • 61,948
  • 13
  • 68
  • 95
  • yeah, it works, but in my case I am using a function from a library, so it's unchangeable. should have mentioned that – Mansur Aug 12 '22 at 06:01