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);
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.
An IIFE should work:
((({ a, b, c }) => someFunction(a, b, c))(obj);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With