Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I do array destructuring assignment inside an object declaration?

Tags:

javascript

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?

like image 900
Larry N Avatar asked Jan 27 '26 01:01

Larry N


2 Answers

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);
like image 194
CertainPerformance Avatar answered Jan 29 '26 16:01

CertainPerformance


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);
like image 29
Nick Parsons Avatar answered Jan 29 '26 14:01

Nick Parsons



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!