Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object destructuring for function calls

Is there a way to destructure a JS object in-place, instead of assigning the destructured variables to a scope?

Instead of doing this:

const { a, b, c } = obj;
someFunction(a, b, c);

I'd like to do this:

someFunction({a, b, c} from obj);

Or something functionally equivalent.

I'd like to do this in situations with these two stipulations:

  • I don't want to put the variable names into the enclosing scope.

  • I don't want to pass the whole object obj, therefore making the spread operator not an option.

The only option I'm left with is to use

someFunction(obj.a, obj.b, obj.c);

Which is fine in this case, but can lower readability when obj is instead a long identifier.

Is something like this possible? I tried using assignment in an expression as a workaround, but my IDE complained that it could not find names a, b, and c:

someFunction({a, b, c} = obj);
like image 742
Anthony Monterrosa Avatar asked Apr 21 '19 03:04

Anthony Monterrosa


2 Answers

One option is to use .map to extract the value of each property you want, and spread it into the argument list:

someFunction(
  ...['a', 'b', 'c'].map(prop => obj[prop])
);

Destructuring requires the creation of intermediate variables, unfortunately, which you don't want.

like image 195
CertainPerformance Avatar answered Oct 20 '22 10:10

CertainPerformance


An IIFE should work:

((({ a, b, c }) => someFunction(a, b, c))(obj);
like image 45
Jack Bashford Avatar answered Oct 20 '22 08:10

Jack Bashford