I know I can do this:
const [MIN_SPEED, MAX_SPEED] = [0.4, 4.0];
What I want is:
const SpeedManager = {
[MIN_SPEED, MAX_SPEED]: [0.4, 4.0]
}
which is equivalent for:
const SpeedManager = {
MIN_SPEED: 0.4,
MAX_SPEED: 4.0
}
but the syntax was invalid, how can I achieve that?
It's not possible - anything involving destructuring will necessary assign values to references (either a standalone variable name, or a nested property). But here, you don't have a reference, at least not while still inside the object initializer.
I'd stick with the non-destructuring method, though an ugly alternative is:
const SpeedManager = {};
([SpeedManager.MIN_SPEED, SpeedManager.MAX_SPEED] = [0.4, 4.0]);
console.log(SpeedManager);
As pointed out, it isn't possible, an alternative could be to zip the two arrays and then use Object.fromEntries() to construct the object for you:
const zip = (arr1, arr2) => arr1.map((e, i) => [e, arr2[i]]);
const res = Object.fromEntries(
zip(['MIN_SPEED', 'MAX_SPEED'], [0.4, 4.0])
);
console.log(res);
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