Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

270
Views
JavaScript spread object as function params

I am trying to spread an object to use as the parameters of a function. I'm pretty sure I've seen this done, but I cant remember how. I know how to do this with an array, but I need to do it with an object. Also, I can't just turn the object into an array using Object.values(obj) since in some cases the order of the values won't match the order of the params.

function sum(x, y, z) {
    return x + y + z
}

obj = {x: 23, y: 52, z: 12}

sum(...obj)  // <--- WHAT DO I PUT HERE?

Using an array, I would just do:

function sum(x, y, z) {
    return x + y + z
}

arr = [23, 52, 12]

sum(...arr)

In python, this would be:

def sum(x, y, z):
    return x + y + z

dict = {'x': 23, 'y': 52, 'z': 12}

sum(**dict)
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Also, I can't just turn the object into an array using Object.values(obj) since in some cases the order of the values won't match the order of the params.

If this is the case, then there's no way to do this without somehow enumerating the desired property order, or by changing the function signature.

function sum(x, y, z) {
    return x + y + z
}
// while this works, it's quite unusual - I don't recommend it
sum.params = ['x', 'y', 'z'];

const obj = {x: 23, y: 52, z: 12}

console.log(sum(...sum.params.map(param => obj[param])));

function sum({ x, y, z }) {
    return x + y + z
}

const obj = {x: 23, y: 52, z: 12}

console.log(sum(obj));

about 4 years ago · Juan Pablo Isaza Report

0

You can catch object fields by name as below

function sum({x,y}) {
    console.log(x + y);
}

obj = {
    x: 5,
    y: 10
}

sum(obj) // output: 15
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!