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
1
  • 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. Commented Aug 12, 2022 at 6:09

2 Answers 2

3

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

fullname(...Object.values(user))
Sign up to request clarification or add additional context in comments.

2 Comments

For this you possibly want to check that object property order is guaranteed for your environment. stackoverflow.com/questions/5525795/…
Try passing user = { 'lastname': 'Wick', 'firstname':'John', } and see the results.
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

1 Comment

yeah, it works, but in my case I am using a function from a library, so it's unchangeable. should have mentioned that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.