-2

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)
user2864740
  • 60,010
  • 15
  • 145
  • 220
ToMakPo
  • 855
  • 7
  • 27
  • There is no way to invoke a JS with arguments “by parameter name”. Usually, one would accept an object as a single argument (with known named properties), in such a case. Destructuring still applies (and it’s still from expanding a single argument, not accepting multiple “by name”). – user2864740 Jan 23 '22 at 00:07
  • `sum(...Object.values(obj))` could be useful? Although you're better of using an object parameter instead. – evolutionxbox Jan 23 '22 at 00:10

2 Answers2

1

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));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Ref. wrt the destructuring usage under “Unpacking fields from objects passed as a function parameter”: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment – user2864740 Jan 23 '22 at 00:12
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