0

I have a function, eg.:

function calculateSize(first, second, third) { ... }

and I want to pass to it an object which looks like this:

const values = {
  first: {
    width: 100,
    height: 100
  },
  second: {
    width: 100,
    height: 100
  },
  third: {
    width: 100,
    height: 100
  }
};

How can I do it in a most succinct way?

bakrall
  • 465
  • 7
  • 21
  • 2
    The safest way is to do `const { first, second, third } = values` and then call `calculateSize(first, second, third)`. – adiga May 25 '21 at 18:56
  • If you're hoping for a "smart" solution, there is none. – georg May 25 '21 at 19:12

2 Answers2

-1

Spread the object values into the function call.

calculateSize(...Object.values(values));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • 1
    It's important to note this only works if you don't care about the order of the arguments – Han Seoul-Oh May 25 '21 at 18:53
  • Sure it does - `Object.values` does have a guaranteed order, given an object, in all but a few pathological cases. Since OP's object's values are defined in the desired order, it'll work. – CertainPerformance May 25 '21 at 18:54
  • 2
    Well, we know the object "looks like* that, but there's no guarantee that one property or another hasn't been added or removed at some point. I tend to regard reliance on property ordering to make some architectural detail work to be a pretty risky idea. – Pointy May 25 '21 at 19:03
-2

You could write like this:

function calculateSize({first, second, third}) { ... }
Guru
  • 139
  • 3